Skip to content

Commit e8fc79d

Browse files
authored
Fix empty relationship data array unmarshal (#41)
Empty relationship data arrays now properly unmarshal into empty Go slices of the desired type, instead of a typed-nil. This is more consistent with the behavior of unmarshal-ing empty primary data arrays.
1 parent 3d76dd3 commit e8fc79d

File tree

2 files changed

+8
-5
lines changed

2 files changed

+8
-5
lines changed

unmarshal.go

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -131,7 +131,7 @@ func unmarshalResourceObjects(ros []*resourceObject, v any, m *Unmarshaler) erro
131131
}
132132

133133
// allocate an empty slice of the outType if there are no resource objects to unmarshal,
134-
// because the main loop cannot construct run and construct one.
134+
// because the main loop cannot construct one.
135135
if len(ros) == 0 {
136136
outValue = reflect.MakeSlice(outType, 0, 0)
137137
}
@@ -253,8 +253,11 @@ func (ro *resourceObject) unmarshalFields(v any, m *Unmarshaler) error {
253253
continue
254254
}
255255
relDocument, ok := ro.Relationships[name]
256-
if !ok || relDocument.isEmpty() {
257-
// relDocument has no relationship data, so there's nothing to do
256+
if !ok {
257+
continue
258+
}
259+
if !relDocument.hasMany && relDocument.isEmpty() {
260+
// ensure struct field is nil for data:null cases only (we want empty slice for data:[])
258261
continue
259262
}
260263

unmarshal_test.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -299,15 +299,15 @@ func TestUnmarshal(t *testing.T) {
299299
expect: &ArticleRelated{},
300300
expectError: ErrRelationshipMissingRequiredMembers,
301301
}, {
302-
// this test verifies that relationship data objects that are null or [] unmarshal
302+
// verifies for empty relationship data: null -> nil and [] -> []Type{}
303303
description: "*ArticleRelated empty relationships data (valid)",
304304
given: articleRelatedNoOmitEmptyBody,
305305
do: func(body []byte) (any, error) {
306306
var a ArticleRelated
307307
err := Unmarshal(body, &a)
308308
return &a, err
309309
},
310-
expect: &ArticleRelated{ID: "1", Title: "A"},
310+
expect: &ArticleRelated{ID: "1", Title: "A", Author: nil, Comments: []*Comment{}},
311311
expectError: nil,
312312
}, {
313313
// this test verifies that empty relationship data objects do not unmarshal

0 commit comments

Comments
 (0)