marshal embedded payload now takes io rather than return struct

This commit is contained in:
Sam Woodard 2015-07-10 17:34:04 -07:00
parent 68c4bcfbb0
commit a6c9e05c33
3 changed files with 43 additions and 9 deletions

View File

@ -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)

View File

@ -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)

View File

@ -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) {