-
Notifications
You must be signed in to change notification settings - Fork 0
/
encode_relationships.go
42 lines (33 loc) · 1.02 KB
/
encode_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
package jsonapi
import (
"encoding/json"
)
type EncodeRelationships map[string]RelationshipDocument
func NewEncodeRelationships(m interface{}) EncodeRelationships {
relatable, ok := m.(Relatable)
if !ok {
return nil
}
relationships := EncodeRelationships{}
multiRelationships := map[string][]Encodable{}
for _, relationship := range relatable.Relationships() {
if relationship.Type == SingularRelationship {
relationships[relationship.Name] = RelationshipDocument{
Data: NewEncodeResourceLinkage(relationship.Resource),
}
} else {
multiRelationships[relationship.Name] = append(multiRelationships[relationship.Name], relationship.Resource)
}
}
for name, encodables := range multiRelationships {
var linkages EncodeResourceLinkages
for _, encodable := range encodables {
linkages = append(linkages, NewEncodeResourceLinkage(encodable))
}
relationships[name] = RelationshipDocument{Data: linkages}
}
return relationships
}
type RelationshipDocument struct {
Data json.Marshaler `json:"data"`
}