-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathencode_resource_object.go
60 lines (51 loc) · 1.62 KB
/
encode_resource_object.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
package jsonapi
import (
"encoding/json"
)
type EncodeResourceObject struct {
Type string
ID string
Attributes EncodeAttributes
Links EncodeLinks
Relationships EncodeRelationships
Meta EncodeMeta
}
func NewEncodeResourceObject(encodable Encodable) EncodeResourceObject {
return EncodeResourceObject{
Type: encodable.Type(),
ID: encodable.Primary(),
Attributes: NewEncodeAttributes(encodable),
Links: NewEncodeLinks(encodable),
Relationships: NewEncodeRelationships(encodable),
Meta: NewEncodeMeta(encodable),
}
}
func (ero EncodeResourceObject) MarshalJSON() ([]byte, error) {
return json.Marshal(struct {
Type string `json:"type"`
ID string `json:"id"`
Attributes EncodeAttributes `json:"attributes,omitempty"`
Links EncodeLinks `json:"links,omitempty"`
Relationships EncodeRelationships `json:"relationships,omitempty"`
Meta EncodeMeta `json:"meta,omitempty"`
}{
Type: ero.Type,
ID: ero.ID,
Attributes: ero.Attributes,
Links: ero.Links,
Relationships: ero.Relationships,
Meta: ero.Meta,
})
}
type EncodeResourceObjects []EncodeResourceObject
func (ero EncodeResourceObjects) MarshalJSON() ([]byte, error) {
marshaledObjects := []json.RawMessage{}
for _, resourceObject := range ero {
marshaledObject, err := json.Marshal(resourceObject)
if err != nil {
return nil, err
}
marshaledObjects = append(marshaledObjects, marshaledObject)
}
return json.Marshal(marshaledObjects)
}