From 103c21c224b28210360a182f25b9691e1adb42bd Mon Sep 17 00:00:00 2001 From: Igor Zibarev Date: Tue, 13 Mar 2018 04:15:16 +0300 Subject: [PATCH] Fix omitempty for attributes (#119) * Fix omitempty for attributes Fix panic on omitempty field for attribute that is not of a primitive type. Fixes #103 * Add more types for omitempty test --- response.go | 2 +- response_test.go | 55 ++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+), 1 deletion(-) diff --git a/response.go b/response.go index bbe6d2c..f6a1b86 100644 --- a/response.go +++ b/response.go @@ -341,7 +341,7 @@ func visitModelNode(model interface{}, included *map[string]*Node, emptyValue := reflect.Zero(fieldValue.Type()) // See if we need to omit this field - if omitEmpty && fieldValue.Interface() == emptyValue.Interface() { + if omitEmpty && reflect.DeepEqual(fieldValue.Interface(), emptyValue.Interface()) { continue } diff --git a/response_test.go b/response_test.go index 9b0bf57..157f434 100644 --- a/response_test.go +++ b/response_test.go @@ -194,6 +194,61 @@ func TestWithOmitsEmptyAnnotationOnRelation_MixedData(t *testing.T) { } } +func TestWithOmitsEmptyAnnotationOnAttribute(t *testing.T) { + type Phone struct { + Number string `json:"number"` + } + + type Address struct { + City string `json:"city"` + Street string `json:"street"` + } + + type Tags map[string]int + + type Author struct { + ID int `jsonapi:"primary,authors"` + Name string `jsonapi:"attr,title"` + Phones []*Phone `jsonapi:"attr,phones,omitempty"` + Address *Address `jsonapi:"attr,address,omitempty"` + Tags Tags `jsonapi:"attr,tags,omitempty"` + } + + author := &Author{ + ID: 999, + Name: "Igor", + Phones: nil, // should be omitted + Address: nil, // should be omitted + Tags: Tags{"dogs": 1, "cats": 2}, // should not be omitted + } + + out := bytes.NewBuffer(nil) + if err := MarshalPayload(out, author); err != nil { + t.Fatal(err) + } + + var jsonData map[string]interface{} + if err := json.Unmarshal(out.Bytes(), &jsonData); err != nil { + t.Fatal(err) + } + + // Verify that there is no field "phones" in attributes + payload := jsonData["data"].(map[string]interface{}) + attributes := payload["attributes"].(map[string]interface{}) + if _, ok := attributes["title"]; !ok { + t.Fatal("Was expecting the data.attributes.title to have NOT been omitted") + } + if _, ok := attributes["phones"]; ok { + t.Fatal("Was expecting the data.attributes.phones to have been omitted") + } + if _, ok := attributes["address"]; ok { + t.Fatal("Was expecting the data.attributes.phones to have been omitted") + } + if _, ok := attributes["tags"]; !ok { + t.Fatal("Was expecting the data.attributes.tags to have NOT been omitted") + } +} + func TestMarshalIDPtr(t *testing.T) { id, make, model := "123e4567-e89b-12d3-a456-426655440000", "Ford", "Mustang" car := &Car{