Skip to content

Commit

Permalink
Fix empty relationship data array unmarshal (#41)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
DQSevilla authored May 24, 2023
1 parent 3d76dd3 commit e8fc79d
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 5 deletions.
9 changes: 6 additions & 3 deletions unmarshal.go
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ func unmarshalResourceObjects(ros []*resourceObject, v any, m *Unmarshaler) erro
}

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

Expand Down
4 changes: 2 additions & 2 deletions unmarshal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -299,15 +299,15 @@ func TestUnmarshal(t *testing.T) {
expect: &ArticleRelated{},
expectError: ErrRelationshipMissingRequiredMembers,
}, {
// this test verifies that relationship data objects that are null or [] unmarshal
// verifies for empty relationship data: null -> nil and [] -> []Type{}
description: "*ArticleRelated empty relationships data (valid)",
given: articleRelatedNoOmitEmptyBody,
do: func(body []byte) (any, error) {
var a ArticleRelated
err := Unmarshal(body, &a)
return &a, err
},
expect: &ArticleRelated{ID: "1", Title: "A"},
expect: &ArticleRelated{ID: "1", Title: "A", Author: nil, Comments: []*Comment{}},
expectError: nil,
}, {
// this test verifies that empty relationship data objects do not unmarshal
Expand Down

0 comments on commit e8fc79d

Please sign in to comment.