From a6c9e05c33afc81102bf5c4b78ace44f40aa6157 Mon Sep 17 00:00:00 2001 From: Sam Woodard Date: Fri, 10 Jul 2015 17:34:04 -0700 Subject: [PATCH] marshal embedded payload now takes io rather than return struct --- examples/app.go | 4 +--- request_test.go | 37 +++++++++++++++++++++++++++++++++++-- response.go | 11 +++++++---- 3 files changed, 43 insertions(+), 9 deletions(-) diff --git a/examples/app.go b/examples/app.go index d935e49..55ee203 100644 --- a/examples/app.go +++ b/examples/app.go @@ -28,10 +28,8 @@ func main() { }) blog := testBlogForCreate() - payload, _ := jsonapi.MarshalOnePayloadEmbedded(blog) - in := bytes.NewBuffer(nil) - json.NewEncoder(in).Encode(payload) + jsonapi.MarshalOnePayloadEmbedded(in, blog) req, _ := http.NewRequest("POST", "/blogs", in) diff --git a/request_test.go b/request_test.go index 69df26a..c63bb63 100644 --- a/request_test.go +++ b/request_test.go @@ -93,6 +93,35 @@ func TestUnmarshalNestedRelationships(t *testing.T) { } } +func TestUnmarshalNestedRelationshipsEmbedded(t *testing.T) { + out := bytes.NewBuffer(nil) + if err := MarshalOnePayloadEmbedded(out, testModel()); err != nil { + t.Fatal(err) + } + + model := new(Blog) + + if err := UnmarshalPayload(out, model); err != nil { + t.Fatal(err) + } + + if model.CurrentPost == nil { + t.Fatalf("Current post was not materialized") + } + + if model.CurrentPost.Comments == nil { + t.Fatalf("Did not materialize nested records, comments") + } + + if len(model.CurrentPost.Comments) != 2 { + t.Fatalf("Wrong number of comments") + } + + if model.CurrentPost.Comments[0].Body != "foo" { + t.Fatalf("Comment body not set") + } +} + func TestUnmarshalRelationshipsSideloaded(t *testing.T) { payload := samplePayloadWithSideloaded() out := new(Blog) @@ -235,8 +264,8 @@ func samplePayloadWithId() io.Reader { return out } -func samplePayloadWithSideloaded() io.Reader { - testModel := &Blog{ +func testModel() *Blog { + return &Blog{ Id: 5, Title: "Title 1", CreatedAt: time.Now(), @@ -288,6 +317,10 @@ func samplePayloadWithSideloaded() io.Reader { }, }, } +} + +func samplePayloadWithSideloaded() io.Reader { + testModel := testModel() out := bytes.NewBuffer(nil) MarshalOnePayload(out, testModel) diff --git a/response.go b/response.go index 0ee35ec..5fb7652 100644 --- a/response.go +++ b/response.go @@ -76,16 +76,19 @@ func MarshalManyPayload(w io.Writer, models Models) error { return nil } -func MarshalOnePayloadEmbedded(model interface{}) (*OnePayload, error) { +func MarshalOnePayloadEmbedded(w io.Writer, model interface{}) error { rootNode, _, err := visitModelNode(model, false) if err != nil { - return nil, err + return err } - resp := &OnePayload{Data: rootNode} + payload := &OnePayload{Data: rootNode} - return resp, nil + if err := json.NewEncoder(w).Encode(payload); err != nil { + return err + } + return nil } func visitModelNode(model interface{}, sideload bool) (*Node, []*Node, error) {