-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdecode_relationships.go
74 lines (61 loc) · 1.56 KB
/
decode_relationships.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
package jsonapi
import (
"encoding/json"
"fmt"
)
type DecodeRelationships struct {
d Decodable
}
func NewDecodeRelationships(d Decodable) DecodeRelationships {
return DecodeRelationships{d}
}
func (dr DecodeRelationships) UnmarshalJSON(data []byte) error {
assignable, ok := dr.d.(RelationshipsAssignable)
if !ok {
return nil
}
var relationshipsMap map[string]interface{}
err := json.Unmarshal(data, &relationshipsMap)
if err != nil {
return err
}
var relationships []Relationship
for name, resource := range relationshipsMap {
r, ok := resource.(map[string]interface{})
if !ok {
return NewDecodeError(dr.d, fmt.Sprintf("relationship %s is not an object", name))
}
switch s := r["data"].(type) {
case map[string]interface{}:
sType, _ := s["type"].(string)
sID, _ := s["id"].(string)
relationships = append(relationships, Relationship{
Name: name,
Type: SingularRelationship,
Resource: DecodeResourceLinkage{
ResourceType: sType,
ID: sID,
},
})
case []interface{}:
for _, item := range s {
t, ok := item.(map[string]interface{})
if !ok {
return NewDecodeError(dr.d, fmt.Sprintf("relationship %s data is not an array of objects", name))
}
tType, _ := t["type"].(string)
tID, _ := t["id"].(string)
relationships = append(relationships, Relationship{
Name: name,
Type: MultiRelationship,
Resource: DecodeResourceLinkage{
ResourceType: tType,
ID: tID,
},
})
}
}
}
assignable.AssignRelationships(relationships)
return nil
}