Skip to content

Commit

Permalink
[FIX] Issue 176 (#199)
Browse files Browse the repository at this point in the history
* fix(request): change the order of the resource data check to prioritise the type when unmarshalling
- fixes #176

* tests(request): update the TestUnmarshalPayload_ptrsAllNil test that broke

* Using %v instead of %s

* Added a test case to demonstrate that this library follows the spec: covered the case where the incoming request payload is missing the `type` field, an error is expected.

Co-authored-by: Aren Patel <[email protected]>
  • Loading branch information
quetzyg and aren55555 authored Mar 6, 2021
1 parent 471426f commit b10ff4b
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 6 deletions.
8 changes: 4 additions & 4 deletions request.go
Original file line number Diff line number Diff line change
Expand Up @@ -175,10 +175,6 @@ func unmarshalNode(data *Node, model reflect.Value, included *map[string]*Node)
}

if annotation == annotationPrimary {
if data.ID == "" {
continue
}

// Check the JSON API Type
if data.Type != args[1] {
er = fmt.Errorf(
Expand All @@ -189,6 +185,10 @@ func unmarshalNode(data *Node, model reflect.Value, included *map[string]*Node)
break
}

if data.ID == "" {
continue
}

// ID will have to be transmitted as astring per the JSON API spec
v := reflect.ValueOf(data.ID)

Expand Down
13 changes: 11 additions & 2 deletions request_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,11 +70,20 @@ func TestUnmarshalToStructWithPointerAttr(t *testing.T) {
}
}

func TestUnmarshalPayload_missingTypeFieldShouldError(t *testing.T) {
if err := UnmarshalPayload(
strings.NewReader(`{"data":{"body":"hello world"}}`),
&Post{},
); err == nil {
t.Fatalf("Expected an error but did not get one")
}
}

func TestUnmarshalPayload_ptrsAllNil(t *testing.T) {
out := new(WithPointer)
if err := UnmarshalPayload(
strings.NewReader(`{"data": {}}`), out); err != nil {
t.Fatalf("Error unmarshalling to Foo")
strings.NewReader(`{"data":{"type":"with-pointers"}}`), out); err != nil {
t.Fatalf("Error unmarshalling to Foo: %v", err)
}

if out.ID != nil {
Expand Down

0 comments on commit b10ff4b

Please sign in to comment.