-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathresponse.go
48 lines (37 loc) · 1.25 KB
/
response.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package goatquery
import (
"encoding/json"
"reflect"
"strings"
)
func BuildPagedResponse[T any](res []T, query Query, totalCount *int64) PagedResponse[map[string]interface{}] {
result := make([]map[string]interface{}, len(res))
selectedProperties := strings.Split(strings.TrimSpace(query.Select), ",")
if query.Select == "" {
bytes, _ := json.Marshal(res)
if err := json.Unmarshal(bytes, &result); err != nil {
return PagedResponse[map[string]interface{}]{Value: result, Count: totalCount}
}
return PagedResponse[map[string]interface{}]{Value: result, Count: totalCount}
}
for i, obj := range res {
newObj := make(map[string]interface{})
v := reflect.ValueOf(obj)
// map over selected properties
for _, p := range selectedProperties {
property := strings.TrimSpace(p)
field, _ := v.Type().FieldByNameFunc(func(p string) bool {
return strings.EqualFold(property, p)
})
name := field.Tag.Get("json")
if name != "" && name != "-" {
// '-' in the json tag means to not return that property
newObj[name] = v.FieldByNameFunc(func(p string) bool {
return strings.EqualFold(property, p)
}).Interface()
}
}
result[i] = newObj
}
return PagedResponse[map[string]interface{}]{Value: result, Count: totalCount}
}