-
Notifications
You must be signed in to change notification settings - Fork 9
/
unmarshal.go
309 lines (263 loc) · 7.84 KB
/
unmarshal.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
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
297
298
299
300
301
302
303
304
305
306
307
308
309
package jsonapi
import (
"encoding"
"encoding/json"
"reflect"
)
// Unmarshaler is configured internally via UnmarshalOption's passed to Unmarshal.
// It's used to configure the Unmarshaling by decoding optional fields like Meta.
type Unmarshaler struct {
unmarshalMeta bool
meta any
memberNameValidationMode memberNameValidationMode
}
// UnmarshalOption allows for configuration of Unmarshaling.
type UnmarshalOption func(m *Unmarshaler)
// UnmarshalMeta decodes Document.Meta into the given interface when unmarshaling.
func UnmarshalMeta(meta any) UnmarshalOption {
return func(m *Unmarshaler) {
m.unmarshalMeta = true
m.meta = meta
}
}
// UnmarshalStrictNameValidation enables member name validation that is more strict than default.
//
// In addition to the basic naming rules from https://jsonapi.org/format/#document-member-names,
// this option follows guidelines from https://jsonapi.org/recommendations/#naming.
func UnmarshalStrictNameValidation() UnmarshalOption {
return func(m *Unmarshaler) {
m.memberNameValidationMode = strictValidation
}
}
// UnmarshalDisableNameValidation turns off member name validation, which may be useful for
// compatibility or performance reasons.
//
// Note that this option allows you to use member names which do not conform to the JSON:API spec.
// See https://jsonapi.org/format/#document-member-names.
func UnmarshalDisableNameValidation() UnmarshalOption {
return func(m *Unmarshaler) {
m.memberNameValidationMode = disableValidation
}
}
// relationshipUnmarshaler creates a new marshaler from a parent one for the sake of unmarshaling
// relationship documents, by copying over relevant fields.
func (m *Unmarshaler) relationshipUnmarshaler() *Unmarshaler {
rm := new(Unmarshaler)
rm.memberNameValidationMode = m.memberNameValidationMode
return rm
}
// Unmarshal parses the json:api encoded data and stores the result in the value pointed to by v.
// If v is nil or not a pointer, Unmarshal returns an error.
func Unmarshal(data []byte, v any, opts ...UnmarshalOption) (err error) {
defer func() {
// because we make use of reflect we must recover any panics
if rvr := recover(); rvr != nil {
err = recoverError(rvr)
return
}
}()
m := new(Unmarshaler)
for _, opt := range opts {
opt(m)
}
rv := reflect.ValueOf(v)
if rv.Kind() != reflect.Pointer || rv.IsNil() {
err = &TypeError{Actual: rv.Kind().String(), Expected: []string{"non-nil pointer"}}
return
}
var d document
if err = json.Unmarshal(data, &d); err != nil {
return
}
if err = validateJSONMemberNames(data, m.memberNameValidationMode); err != nil {
return
}
err = d.unmarshal(v, m)
return
}
func (d *document) unmarshal(v any, m *Unmarshaler) (err error) {
// this means we couldn't decode anything (e.g. {}, [], ...)
if d.isEmpty() {
err = &RequestBodyError{t: v}
return
}
// verify full-linkage in-case this is a compound document
if err = d.verifyFullLinkage(true); err != nil {
return
}
if d.hasMany {
err = unmarshalResourceObjects(d.DataMany, v, m)
if err != nil {
return
}
} else {
err = d.DataOne.unmarshal(v, m)
if err != nil {
return
}
}
err = d.unmarshalOptionalFields(m)
return
}
func (d *document) unmarshalOptionalFields(m *Unmarshaler) error {
if m == nil {
// this is possible during recursive document unmarshaling
return nil
}
if m.unmarshalMeta {
b, err := json.Marshal(d.Meta)
if err != nil {
return err
}
if err := json.Unmarshal(b, m.meta); err != nil {
return err
}
if err := validateJSONMemberNames(b, m.memberNameValidationMode); err != nil {
return err
}
}
return nil
}
func unmarshalResourceObjects(ros []*resourceObject, v any, m *Unmarshaler) error {
outType := derefType(reflect.TypeOf(v))
outValue := derefValue(reflect.ValueOf(v))
// first, it must be a struct since we'll be parsing the jsonapi struct tags
if outType.Kind() != reflect.Slice {
return &TypeError{Actual: outType.String(), Expected: []string{"slice"}}
}
for _, ro := range ros {
// unmarshal the resource object into an empty value of the slices element type
outElem := reflect.New(derefType(outType.Elem())).Interface()
if err := ro.unmarshal(outElem, m); err != nil {
return err
}
// reflect.New creates a pointer, so if our slices underlying type
// is not a pointer we must dereference the value before appending it
outElemValue := reflect.ValueOf(outElem)
if outType.Elem().Kind() != reflect.Pointer {
outElemValue = derefValue(outElemValue)
}
// append the unmarshaled resource object to the result slice
outValue = reflect.Append(outValue, outElemValue)
}
// set the value of the passed in object to our result
reflect.ValueOf(v).Elem().Set(outValue)
return nil
}
func (ro *resourceObject) unmarshal(v any, m *Unmarshaler) error {
// first, it must be a struct since we'll be parsing the jsonapi struct tags
vt := reflect.TypeOf(v)
if derefType(vt).Kind() != reflect.Struct {
return &TypeError{Actual: vt.String(), Expected: []string{"struct"}}
}
if err := ro.unmarshalFields(v, m); err != nil {
return err
}
return ro.unmarshalAttributes(v)
}
// unmarshalFields unmarshals a resource object into all non-attribute struct fields
func (ro *resourceObject) unmarshalFields(v any, m *Unmarshaler) error {
setPrimary := false
rv := derefValue(reflect.ValueOf(v))
rt := reflect.TypeOf(rv.Interface())
for i := 0; i < rv.NumField(); i++ {
fv := rv.Field(i)
ft := rt.Field(i)
jsonapiTag, err := parseJSONAPITag(ft)
if err != nil {
return err
}
if jsonapiTag == nil {
continue
}
switch jsonapiTag.directive {
case primary:
if setPrimary {
return ErrUnmarshalDuplicatePrimaryField
}
if ro.Type != jsonapiTag.resourceType {
return &TypeError{Actual: ro.Type, Expected: []string{jsonapiTag.resourceType}}
}
if !isValidMemberName(ro.Type, m.memberNameValidationMode) {
// type names count as member names
return &MemberNameValidationError{ro.Type}
}
// if omitempty is allowed, skip if this is an empty id
if jsonapiTag.omitEmpty && ro.ID == "" {
continue
}
// to unmarshal the id we follow these rules
// 1. Use UnmarshalIdentifier if it is implemented
// 2. Use encoding.TextUnmarshaler if it is implemented
// 3. Use the value directly if it is a string
// 4. Fail
if vu, ok := v.(UnmarshalIdentifier); ok {
if err := vu.UnmarshalID(ro.ID); err != nil {
return err
}
setPrimary = true
continue
}
// get the underlying fields interface
var fvi any
switch fv.CanAddr() {
case true:
fvi = fv.Addr().Interface()
default:
fvi = fv.Interface()
}
if fviu, ok := fvi.(encoding.TextUnmarshaler); ok {
if err := fviu.UnmarshalText([]byte(ro.ID)); err != nil {
return err
}
setPrimary = true
continue
}
if fv.Kind() == reflect.String {
fv.SetString(ro.ID)
setPrimary = true
continue
}
return ErrUnmarshalInvalidPrimaryField
case relationship:
name, exported, _ := parseJSONTag(ft)
if !exported {
continue
}
relDocument, ok := ro.Relationships[name]
if !ok || relDocument.isEmpty() {
// relDocument has no relationship data, so there's nothing to do
continue
}
rm := m.relationshipUnmarshaler()
rel := reflect.New(derefType(ft.Type)).Interface()
if err := relDocument.unmarshal(rel, rm); err != nil {
return err
}
setFieldValue(fv, rel)
case meta:
if ro.Meta == nil {
continue
}
b, err := json.Marshal(ro.Meta)
if err != nil {
return err
}
meta := reflect.New(derefType(ft.Type)).Interface()
if err = json.Unmarshal(b, meta); err != nil {
return err
}
setFieldValue(fv, meta)
default:
continue
}
}
return nil
}
func (ro *resourceObject) unmarshalAttributes(v any) error {
b, err := json.Marshal(ro.Attributes)
if err != nil {
return err
}
return json.Unmarshal(b, v)
}