Skip to content

Commit 662431e

Browse files
skimataaren55555
authored andcommitted
Feature/embeded structs fix tests (#105)
* fix TestEmbededStructs_nonNilStructPtr; bug on loop w/ (multiple) embedded structs; should just continue on success * fix TestMarshal_duplicatePrimaryAnnotationFromEmbeddedStructs; fix order of processing of visitModelNode
1 parent 5be0508 commit 662431e

File tree

2 files changed

+27
-6
lines changed

2 files changed

+27
-6
lines changed

request.go

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -218,10 +218,12 @@ func unmarshalNode(data *Node, model reflect.Value, included *map[string]*Node)
218218
assign(em.structField, tmp)
219219
data = copy
220220
}
221-
return nil
221+
} else {
222+
// handle non-nil scenarios
223+
if err := unmarshalNode(data, em.model, included); err != nil {
224+
return err
225+
}
222226
}
223-
// handle non-nil scenarios
224-
return unmarshalNode(data, em.model, included)
225227
}
226228

227229
return nil

response.go

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -202,21 +202,24 @@ func MarshalOnePayloadEmbedded(w io.Writer, model interface{}) error {
202202
return nil
203203
}
204204

205-
func visitModelNode(model interface{}, included *map[string]*Node,
206-
sideload bool) (*Node, error) {
205+
// visitModelNode converts models to jsonapi payloads
206+
// it handles the deepest models first. (i.e.) embedded models
207+
// this is so that upper-level attributes can overwrite lower-level attributes
208+
func visitModelNode(model interface{}, included *map[string]*Node, sideload bool) (*Node, error) {
207209
node := new(Node)
208210

209211
var er error
210212

211213
modelValue := reflect.ValueOf(model).Elem()
212214
modelType := reflect.ValueOf(model).Type().Elem()
213215

216+
// handle just the embedded models first
214217
for i := 0; i < modelValue.NumField(); i++ {
215218
fieldValue := modelValue.Field(i)
216219
fieldType := modelType.Field(i)
217220

221+
// skip if annotated w/ ignore
218222
tag := fieldType.Tag.Get(annotationJSONAPI)
219-
220223
if shouldIgnoreField(tag) {
221224
continue
222225
}
@@ -239,6 +242,22 @@ func visitModelNode(model interface{}, included *map[string]*Node,
239242
break
240243
}
241244
node.merge(embNode)
245+
}
246+
}
247+
248+
// handle everthing else
249+
for i := 0; i < modelValue.NumField(); i++ {
250+
fieldValue := modelValue.Field(i)
251+
fieldType := modelType.Field(i)
252+
253+
tag := fieldType.Tag.Get(annotationJSONAPI)
254+
255+
if shouldIgnoreField(tag) {
256+
continue
257+
}
258+
259+
// skip embedded because it was handled in a previous loop
260+
if isEmbeddedStruct(fieldType) || isEmbeddedStructPtr(fieldType) {
242261
continue
243262
}
244263

0 commit comments

Comments
 (0)