From db9617ef6fc52329bad8e4c40440b2113691f416 Mon Sep 17 00:00:00 2001 From: Sam Woodard Date: Thu, 9 Jul 2015 12:07:33 -0700 Subject: [PATCH] omit zero times from the response --- response.go | 6 ++++++ response_test.go | 23 +++++++++++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/response.go b/response.go index d83717a..76ef78e 100644 --- a/response.go +++ b/response.go @@ -123,6 +123,12 @@ func visitModelNode(model interface{}, sideload bool) (*JsonApiNode, []*JsonApiN if len(args) >= 2 { if fieldValue.Type() == reflect.TypeOf(time.Time{}) { + isZeroMethod := fieldValue.MethodByName("IsZero") + isZero := isZeroMethod.Call(make([]reflect.Value, 0))[0].Interface().(bool) + if isZero { + return false + } + unix := fieldValue.MethodByName("Unix") val := unix.Call(make([]reflect.Value, 0))[0] node.Attributes[args[1]] = val.Int() diff --git a/response_test.go b/response_test.go index 7b69839..1ec5127 100644 --- a/response_test.go +++ b/response_test.go @@ -102,6 +102,29 @@ func TestSupportsAttributes(t *testing.T) { } } +func TestOmitsZeroTimes(t *testing.T) { + testModel := &Blog{ + Id: 5, + Title: "Title 1", + CreatedAt: time.Time{}, + } + + resp, err := MarshalJsonApiOnePayload(testModel) + if err != nil { + t.Fatal(err) + } + + response := resp.Data + + if response.Attributes == nil { + t.Fatalf("Expected attributes") + } + + if response.Attributes["created_at"] != nil { + t.Fatalf("Created at was serialized even though it was a zero Time") + } +} + func TestRelations(t *testing.T) { testModel := &Blog{ Id: 5,