1
0
mirror of https://github.com/beego/bee.git synced 2024-11-10 15:00:54 +00:00

trim unused fields in result json

This commit is contained in:
ZhengYang 2014-08-05 17:49:36 +08:00
parent d02a552a59
commit b057b16a80

View File

@ -627,7 +627,7 @@ func Get{{modelName}}ById(id int) (v *{{modelName}}, err error) {
// GetAll{{modelName}} retrieves all {{modelName}} matches certain condition. Returns empty list if // GetAll{{modelName}} retrieves all {{modelName}} matches certain condition. Returns empty list if
// no records exist // no records exist
func GetAll{{modelName}}(query map[string]string, fields []string, sortby []string, order []string, func GetAll{{modelName}}(query map[string]string, fields []string, sortby []string, order []string,
offset int64, limit int64) (l []{{modelName}}, err error) { offset int64, limit int64) (ml []interface{}, err error) {
o := orm.NewOrm() o := orm.NewOrm()
qs := o.QueryTable(new({{modelName}})) qs := o.QueryTable(new({{modelName}}))
// query k=v // query k=v
@ -675,9 +675,26 @@ func GetAll{{modelName}}(query map[string]string, fields []string, sortby []stri
} }
} }
var l []{{modelName}}
qs = qs.OrderBy(sortFields...) qs = qs.OrderBy(sortFields...)
if _, err := qs.Limit(limit, offset).All(&l, fields...); err == nil { if _, err := qs.Limit(limit, offset).All(&l, fields...); err == nil {
return l, nil // trim unused fields
fieldMap := make(map[string]interface{})
for _, v := range fields {
fieldMap[v] = true
}
for _, v := range l {
s := reflect.Indirect(reflect.ValueOf(v))
typeOfS := s.Type()
for i := 0; i < s.NumField(); i++ {
f := s.Field(i)
if _, ok := fieldMap[typeOfS.Field(i).Name]; ok {
fieldMap[typeOfS.Field(i).Name] = f.Interface()
}
}
}
ml = append(ml, fieldMap)
return ml, nil
} }
return nil, err return nil, err
} }