Commit ff16e649 authored by zauberstuhl's avatar zauberstuhl

Add SelectFields to post model

If you need only a view fields instead
of the whole struct. The json dash tag is
not sufficent enough since we cannot adjust
it dynamically
parent a9f0f3b6
...@@ -20,6 +20,7 @@ package models ...@@ -20,6 +20,7 @@ package models
import ( import (
"time" "time"
"github.com/jinzhu/gorm" "github.com/jinzhu/gorm"
"github.com/fatih/structs"
federation "gopkg.in/ganggo/federation.v0" federation "gopkg.in/ganggo/federation.v0"
) )
...@@ -109,6 +110,33 @@ func (p *Post) AfterCreate(db *gorm.DB) error { ...@@ -109,6 +110,33 @@ func (p *Post) AfterCreate(db *gorm.DB) error {
return err return err
} }
// select only a few fields instead of the whole struct
// this can optimize mobile app performance if on slow networks
func (p Posts) SelectFields(fields... string) (m map[int]interface{}) {
m = make(map[int]interface{}, len(p))
for i, post := range p {
m[i] = post.SelectFields(fields...)
}
return
}
func (p Post) SelectFields(fields... string) (m map[string]interface{}) {
// check if first element is empty even if len() == 1
// in case empty field parameter was submitted
if len(fields) <= 0 || fields[0] == "" {
return structs.Map(&p)
}
m = make(map[string]interface{}, len(fields))
postMap := structs.Map(&p)
for _, field := range fields {
if _, ok := postMap[field]; ok {
m[field] = postMap[field]
}
}
return
}
func (p *Post) Count() (count int, err error) { func (p *Post) Count() (count int, err error) {
db, err := OpenDatabase() db, err := OpenDatabase()
if err != nil { if err != nil {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment