-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmarshal.go
More file actions
296 lines (265 loc) · 8.4 KB
/
marshal.go
File metadata and controls
296 lines (265 loc) · 8.4 KB
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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
package jsonapi
import (
"encoding/json"
"io"
"path"
"time"
neuronCodec "github.com/neuronlabs/neuron/codec"
"github.com/neuronlabs/neuron/errors"
"github.com/neuronlabs/neuron/log"
"github.com/neuronlabs/neuron/mapping"
)
// ErrorsPayload is a serializer struct for representing a valid JSON API errors payload.
type ErrorsPayload struct {
JSONAPI map[string]interface{} `json:"jsonapi,omitempty"`
Errors []*neuronCodec.Error `json:"errors"`
}
// Marshal marshals provided value 'v' into writer 'w'
func marshalPayload(w io.Writer, payload Payloader) error {
err := json.NewEncoder(w).Encode(payload)
if err != nil {
return err
}
return nil
}
func (c Codec) visitModels(models []mapping.Model, linkOptions neuronCodec.LinkOptions) (nodes []*Node, err error) {
var mStruct *mapping.ModelStruct
for _, model := range models {
if model == nil {
continue
}
mStruct, err = c.c.ModelStruct(model)
if err != nil {
return nil, err
}
node, err := visitModelNode(mStruct, model, linkOptions, mStruct.StructFields()...)
if err != nil {
return nil, err
}
nodes = append(nodes, node)
}
return nodes, nil
}
func (c Codec) visitPayloadModels(payload *neuronCodec.Payload) (nodes []*Node, err error) {
nodes = make([]*Node, len(payload.Data))
var mStruct *mapping.ModelStruct
var commonFieldset mapping.FieldSet
switch len(payload.FieldSets) {
case 0:
commonFieldset = append(payload.ModelStruct.Attributes(), payload.ModelStruct.RelationFields()...)
for _, relation := range payload.IncludedRelations {
commonFieldset = append(commonFieldset, relation.StructField)
}
case 1:
commonFieldset = payload.FieldSets[0]
// Add all included relations.
for _, relation := range payload.IncludedRelations {
if len(relation.Fieldset) > 0 {
commonFieldset = append(commonFieldset, relation.StructField)
}
}
case len(payload.Data):
default:
return nil, errors.WrapDetf(neuronCodec.ErrMarshalPayload, "provided invalid payload fieldset number")
}
for i, model := range payload.Data {
var fieldSet mapping.FieldSet
if commonFieldset != nil {
fieldSet = commonFieldset
} else {
fieldSet = payload.FieldSets[i]
for _, relation := range payload.IncludedRelations {
if len(relation.Fieldset) > 0 {
fieldSet = append(fieldSet, relation.StructField)
}
}
}
mStruct, err = c.c.ModelStruct(model)
if err != nil {
return nil, err
}
if mStruct != payload.ModelStruct {
return nil, errors.WrapDet(neuronCodec.ErrMarshal, "expecting payload with single model type - provided multiple type models")
}
node, err := visitModelNode(mStruct, model, payload.MarshalLinks, fieldSet...)
if err != nil {
return nil, err
}
nodes[i] = node
}
return nodes, nil
}
func visitModelNode(mStruct *mapping.ModelStruct, model mapping.Model, linkOptions neuronCodec.LinkOptions, fieldSet ...*mapping.StructField) (node *Node, err error) {
node = &Node{Type: mStruct.Collection()}
// set primary
primStruct := mStruct.Primary()
if !primStruct.CodecSkip() && !model.IsPrimaryKeyZero() {
node.ID, err = model.GetPrimaryKeyStringValue()
if err != nil {
return nil, err
}
}
var (
fielder mapping.Fielder
multiRelationer mapping.MultiRelationer
singleRelationer mapping.SingleRelationer
ok bool
)
for _, field := range fieldSet {
// if the field is mark as hidden or '-' do not marshal that field.
if field.CodecSkip() {
if log.CurrentLevel().IsAllowed(log.LevelDebug3) {
log.Debug3f("jsonapi marshal: %s - field: %s not marshaled - is hidden", mStruct, field.NeuronName())
}
continue
}
fieldName := field.CodecName()
// extract field's value
// marshal differently for different field type
switch field.Kind() {
case mapping.KindAttribute:
if field.IsNestedStruct() {
// node.Attributes[fieldName] = marshalNestedStructValue(field.Nested(), fieldValue).Interface()
continue
}
if node.Attributes == nil {
node.Attributes = make(map[string]interface{})
}
if fielder == nil {
fielder, ok = model.(mapping.Fielder)
if !ok {
return nil, errors.Wrap(mapping.ErrModelNotImplements, "model doesn't implement fielder interface")
}
}
// Check if field has zero value.
isZero, err := fielder.IsFieldZero(field)
if err != nil {
return nil, err
}
fieldValue, err := fielder.GetFieldValue(field)
if err != nil {
return nil, err
}
if field.CodecOmitEmpty() && isZero {
if log.CurrentLevel().IsAllowed(log.LevelDebug3) {
log.Debug3f("jsonapi marshal: %s - field: %s empty value omitted", mStruct, field.NeuronName())
}
continue
}
if field.IsPtr() && isZero {
node.Attributes[fieldName] = nil
continue
}
if !field.IsTime() {
node.Attributes[fieldName] = fieldValue
continue
}
var t time.Time
if field.IsPtr() {
t = *fieldValue.(*time.Time)
} else {
t = fieldValue.(time.Time)
}
if t.IsZero() && field.CodecOmitEmpty() {
if log.CurrentLevel().IsAllowed(log.LevelDebug3) {
log.Debug3f("jsonapi marshal: %s - field: %s empty value omitted", mStruct, field.NeuronName())
}
continue
}
if field.IsISO8601() {
if log.CurrentLevel().IsAllowed(log.LevelDebug3) {
log.Debug3f("jsonapi marshal: %s - field: %s marshal time field using ISO8601 format", mStruct, field.NeuronName())
}
node.Attributes[fieldName] = t.UTC().Format(neuronCodec.ISO8601TimeFormat)
} else {
node.Attributes[fieldName] = t.Unix()
}
case mapping.KindRelationshipMultiple:
if multiRelationer == nil {
multiRelationer, ok = model.(mapping.MultiRelationer)
if !ok {
return nil, errors.Wrap(mapping.ErrModelNotImplements, "model doesn't implement MultiRelationer")
}
}
relationLen, err := multiRelationer.GetRelationLen(field)
if err != nil {
return nil, err
}
if field.CodecOmitEmpty() && relationLen == 0 {
if log.CurrentLevel().IsAllowed(log.LevelDebug3) {
log.Debug3f("jsonapi marshal: %s - field: %s empty value omitted", mStruct, field.NeuronName())
}
continue
}
if node.Relationships == nil {
node.Relationships = make(map[string]interface{})
}
relations, err := multiRelationer.GetRelationModels(field)
if err != nil {
return nil, err
}
r := &RelationshipManyNode{
Data: make([]*Node, relationLen),
}
var id string
for i, relation := range relations {
id, err = relation.GetPrimaryKeyStringValue()
if err != nil {
return nil, err
}
r.Data[i] = &Node{Type: relation.NeuronCollectionName(), ID: id}
}
if linkOptions.Type == neuronCodec.ResourceLink {
link := make(map[string]interface{})
link["self"] = path.Join(linkOptions.BaseURL, mStruct.Collection(), node.ID, "relationships", fieldName)
link["related"] = path.Join(linkOptions.BaseURL, mStruct.Collection(), node.ID, fieldName)
links := Links(link)
r.Links = &links
}
node.Relationships[fieldName] = r
case mapping.KindRelationshipSingle:
if singleRelationer == nil {
singleRelationer, ok = model.(mapping.SingleRelationer)
if !ok {
return nil, errors.Wrap(mapping.ErrModelNotImplements, "model doesn't implement SingleRelationer")
}
}
relation, err := singleRelationer.GetRelationModel(field)
if err != nil {
return nil, err
}
if field.CodecOmitEmpty() && relation == nil {
if log.CurrentLevel().IsAllowed(log.LevelDebug3) {
log.Debug3f("jsonapi marshal: %s - field: %s empty value omitted", mStruct, field.NeuronName())
}
continue
}
if node.Relationships == nil {
node.Relationships = make(map[string]interface{})
}
r := &RelationshipOneNode{}
if linkOptions.Type == neuronCodec.ResourceLink {
link := make(map[string]interface{})
link["self"] = path.Join(linkOptions.BaseURL, mStruct.Collection(), node.ID, "relationships", fieldName)
link["related"] = path.Join(linkOptions.BaseURL, mStruct.Collection(), node.ID, fieldName)
links := Links(link)
r.Links = &links
}
if relation != nil {
id, err := relation.GetPrimaryKeyStringValue()
if err != nil {
return nil, err
}
r.Data = &Node{Type: relation.NeuronCollectionName(), ID: id}
}
node.Relationships[fieldName] = r
}
}
if linkOptions.Type == neuronCodec.ResourceLink {
links := make(map[string]interface{})
links["self"] = path.Join(linkOptions.BaseURL, mStruct.Collection(), node.ID)
linksObj := Links(links)
node.Links = &(linksObj)
}
return node, nil
}