forked from grafana/k6
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgroup_jsonapi.go
118 lines (97 loc) · 2.47 KB
/
group_jsonapi.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
package v1
import "encoding/json"
type groupJSONAPI struct {
Data groupData `json:"data"`
}
type groupsJSONAPI struct {
Data []groupData `json:"data"`
}
type groupData struct {
Type string `json:"type"`
ID string `json:"id"`
Attributes Group `json:"attributes"`
Relationships groupRelations `json:"relationships"`
}
type groupRelations struct {
Groups struct {
Data []groupRelation `json:"data"`
} `json:"groups"`
Parent struct {
Data *groupRelation `json:"data"`
} `json:"parent"`
}
type groupRelation struct {
Type string `json:"type"`
ID string `json:"id"`
}
// UnmarshalJSON unmarshal group data properly (extract the ID)
func (g *groupData) UnmarshalJSON(data []byte) error {
var raw struct {
Type string `json:"type"`
ID string `json:"id"`
Attributes Group `json:"attributes"`
Relationships groupRelations `json:"relationships"`
}
if err := json.Unmarshal(data, &raw); err != nil {
return err
}
g.ID = raw.ID
g.Type = raw.Type
g.Relationships = raw.Relationships
g.Attributes = raw.Attributes
if g.Attributes.ID == "" {
g.Attributes.ID = raw.ID
}
if g.Relationships.Parent.Data != nil {
g.Attributes.ParentID = g.Relationships.Parent.Data.ID
}
g.Attributes.GroupIDs = make([]string, 0, len(g.Relationships.Groups.Data))
for _, rel := range g.Relationships.Groups.Data {
g.Attributes.GroupIDs = append(g.Attributes.GroupIDs, rel.ID)
}
return nil
}
func newGroupJSONAPI(g *Group) groupJSONAPI {
return groupJSONAPI{
Data: newGroupData(g),
}
}
func newGroupsJSONAPI(groups []*Group) groupsJSONAPI {
envelop := groupsJSONAPI{
Data: make([]groupData, 0, len(groups)),
}
for _, g := range groups {
envelop.Data = append(envelop.Data, newGroupData(g))
}
return envelop
}
func newGroupData(group *Group) groupData {
data := groupData{
Type: "groups",
ID: group.ID,
Attributes: *group,
Relationships: groupRelations{
Groups: struct {
Data []groupRelation `json:"data"`
}{
Data: make([]groupRelation, 0, len(group.Groups)),
},
Parent: struct {
Data *groupRelation `json:"data"`
}{},
},
}
if group.Parent != nil {
data.Relationships.Parent.Data = &groupRelation{
Type: "groups",
ID: group.Parent.ID,
}
}
for _, gp := range group.Groups {
data.Relationships.Groups.Data = append(data.Relationships.Groups.Data, groupRelation{
ID: gp.ID,
Type: "groups",
})
}
return data
}