forked from infobloxopen/atlas-app-toolkit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfields.go
84 lines (76 loc) · 1.92 KB
/
fields.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package gateway
import (
"context"
"net/http"
"github.com/infobloxopen/atlas-app-toolkit/query"
)
//retainFields function extracts the configuration for fields that
//need to be ratained either from gRPC response or from original testRequest
//(in case when gRPC side didn't set any preferences) and retains only
//this fields on outgoing response (dynmap).
func retainFields(ctx context.Context, req *http.Request, dynmap map[string]interface{}) {
fieldsStr := ""
if req != nil {
//no fields in gprc response -> try to get from original testRequest
vals := req.URL.Query()
fieldsStr = vals.Get(fieldsQueryKey)
}
if fieldsStr == "" {
return
}
fields := query.ParseFieldSelection(fieldsStr)
if fields != nil {
for k, result := range dynmap {
if k != "page" {
if results, ok := result.([]interface{}); ok {
for _, r := range results {
if m, ok := r.(map[string]interface{}); ok {
doRetainFields(m, fields.Fields)
}
}
} else if m, ok := result.(map[string]interface{}); ok {
doRetainFields(m, fields.Fields)
}
}
}
}
}
func doRetainFields(obj map[string]interface{}, fields query.FieldSelectionMap) {
if fields == nil || len(fields) == 0 {
return
}
_, unassoc := fields["_unassoc"]
_, assoc := fields["_assoc"]
for key := range obj {
if _, ok := fields["!"+key]; ok {
delete(obj, key)
}
if _, ok := fields[key]; !ok {
if _, isModel := obj[key].(map[string]interface{}); isModel {
if assoc {
continue
}
} else {
if unassoc {
continue
}
}
delete(obj, key)
} else {
switch x := obj[key].(type) {
case map[string]interface{}:
fds := fields[key].Subs
if fds != nil && len(fds) > 0 {
doRetainFields(x, fds)
}
case []interface{}:
for _, r := range obj[key].([]interface{}) {
if m, ok := r.(map[string]interface{}); ok {
fds := fields[key].Subs
doRetainFields(m, fds)
}
}
}
}
}
}