Skip to content

Commit e32c6a1

Browse files
quetzygaren55555
authored andcommitted
[FIX] Issue 176 (google#199)
* fix(request): change the order of the resource data check to prioritise the type when unmarshalling - fixes google#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]>
1 parent 3e7cb9e commit e32c6a1

File tree

2 files changed

+15
-6
lines changed

2 files changed

+15
-6
lines changed

request.go

+4-4
Original file line numberDiff line numberDiff line change
@@ -175,10 +175,6 @@ func unmarshalNode(data *Node, model reflect.Value, included *map[string]*Node)
175175
}
176176

177177
if annotation == annotationPrimary {
178-
if data.ID == "" {
179-
continue
180-
}
181-
182178
// Check the JSON API Type
183179
if data.Type != args[1] {
184180
er = fmt.Errorf(
@@ -189,6 +185,10 @@ func unmarshalNode(data *Node, model reflect.Value, included *map[string]*Node)
189185
break
190186
}
191187

188+
if data.ID == "" {
189+
continue
190+
}
191+
192192
// ID will have to be transmitted as astring per the JSON API spec
193193
v := reflect.ValueOf(data.ID)
194194

request_test.go

+11-2
Original file line numberDiff line numberDiff line change
@@ -70,11 +70,20 @@ func TestUnmarshalToStructWithPointerAttr(t *testing.T) {
7070
}
7171
}
7272

73+
func TestUnmarshalPayload_missingTypeFieldShouldError(t *testing.T) {
74+
if err := UnmarshalPayload(
75+
strings.NewReader(`{"data":{"body":"hello world"}}`),
76+
&Post{},
77+
); err == nil {
78+
t.Fatalf("Expected an error but did not get one")
79+
}
80+
}
81+
7382
func TestUnmarshalPayload_ptrsAllNil(t *testing.T) {
7483
out := new(WithPointer)
7584
if err := UnmarshalPayload(
76-
strings.NewReader(`{"data": {}}`), out); err != nil {
77-
t.Fatalf("Error unmarshalling to Foo")
85+
strings.NewReader(`{"data":{"type":"with-pointers"}}`), out); err != nil {
86+
t.Fatalf("Error unmarshalling to Foo: %v", err)
7887
}
7988

8089
if out.ID != nil {

0 commit comments

Comments
 (0)