-
Notifications
You must be signed in to change notification settings - Fork 9
/
unmarshal.go
248 lines (211 loc) · 5.74 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
package jsonapi
import (
"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
}
// 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
}
}
// 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
err = json.Unmarshal(data, &d)
if 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 len(d.DataMany) == 0 && d.DataOne == nil {
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)
if err != nil {
return
}
} else {
err = d.DataOne.unmarshal(v)
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
}
}
return nil
}
func unmarshalResourceObjects(ros []*resourceObject, v any) 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); 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) 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); err != nil {
return err
}
if err := ro.unmarshalAttributes(v); err != nil {
return err
}
return nil
}
// unmarshalFields unmarshals a resource object into all non-attribute struct fields
func (ro *resourceObject) unmarshalFields(v any) 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}}
}
// to unmarshal the id we follow these rules
// 1. Use UnmarshalIdentifier if it is implemented
// 2. Use the value directly if it is a string
// 3. Fail
if vu, ok := v.(UnmarshalIdentifier); ok {
if err := vu.UnmarshalID(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 has no relationship data, so there's nothing to do
continue
}
rel := reflect.New(derefType(ft.Type)).Interface()
if err := relDocument.unmarshal(rel, nil); 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
}
if err := json.Unmarshal(b, v); err != nil {
return err
}
return nil
}