From ed08d4f02a4dd48caa526df5702bdc3bc837b578 Mon Sep 17 00:00:00 2001 From: Sam Woodard Date: Fri, 5 Oct 2018 08:57:33 -0700 Subject: [PATCH] refactor, consistency, add test to ensure we don't need additional type check --- request.go | 13 +++++-------- request_test.go | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+), 8 deletions(-) diff --git a/request.go b/request.go index 93275a7..a7bb0b1 100644 --- a/request.go +++ b/request.go @@ -253,11 +253,7 @@ func unmarshalNode(data *Node, model reflect.Value, included *map[string]*Node) break } - // As a final catch-all, ensure types line up to avoid a runtime panic. - if fieldValue.Kind() != value.Kind() { - return ErrInvalidType - } - assignValue(fieldValue, value) + assign(fieldValue, value) } else if annotation == annotationRelation { isSlice := fieldValue.Type().Kind() == reflect.Slice @@ -355,10 +351,11 @@ func assign(field, value reflect.Value) { // initialize pointer so it's value // can be set by assignValue field.Set(reflect.New(field.Type().Elem())) - assignValue(field.Elem(), value) - } else { - assignValue(field, value) + field = field.Elem() + } + + assignValue(field, value) } // assign assigns the specified value to the field, diff --git a/request_test.go b/request_test.go index 6e7870b..3326598 100644 --- a/request_test.go +++ b/request_test.go @@ -822,6 +822,38 @@ func TestUnmarshalCustomTypeAttributes(t *testing.T) { } } +func TestUnmarshalCustomTypeAttributes_ErrInvalidType(t *testing.T) { + data := map[string]interface{}{ + "data": map[string]interface{}{ + "type": "customtypes", + "id": "1", + "attributes": map[string]interface{}{ + "int": "bad", + "intptr": 5, + "intptrnull": nil, + + "float": 1.5, + "string": "Test", + }, + }, + } + payload, err := json.Marshal(data) + if err != nil { + t.Fatal(err) + } + + // Parse JSON API payload + customAttributeTypes := new(CustomAttributeTypes) + err = UnmarshalPayload(bytes.NewReader(payload), customAttributeTypes) + if err == nil { + t.Fatal("Expected an error unmarshalling the payload due to type mismatch, got none") + } + + if err != ErrInvalidType { + t.Fatalf("Expected error to be %v, was %v", ErrInvalidType, err) + } +} + func samplePayloadWithoutIncluded() map[string]interface{} { return map[string]interface{}{ "data": map[string]interface{}{