diff --git a/jsonapi/data_structs.go b/jsonapi/data_structs.go index 5d7ac78..279b6cf 100644 --- a/jsonapi/data_structs.go +++ b/jsonapi/data_structs.go @@ -120,6 +120,7 @@ type Data struct { Attributes json.RawMessage `json:"attributes"` Relationships map[string]Relationship `json:"relationships,omitempty"` Links Links `json:"links,omitempty"` + Meta json.RawMessage `json:"meta,omitempty"` } // Relationship contains reference IDs to the related structs diff --git a/jsonapi/fixtures_test.go b/jsonapi/fixtures_test.go index 0f82d7f..abc34b6 100644 --- a/jsonapi/fixtures_test.go +++ b/jsonapi/fixtures_test.go @@ -500,6 +500,24 @@ func (n CustomLinksPost) GetCustomLinks(base string) Links { } } +type CustomResourceMetaPost struct{} + +func (n CustomResourceMetaPost) GetID() string { + return "someID" +} + +func (n *CustomResourceMetaPost) SetID(ID string) error { + return nil +} + +func (n CustomResourceMetaPost) GetName() string { + return "posts" +} + +func (n CustomResourceMetaPost) Meta() Meta { + return Meta{"access_count": 15} +} + type CustomMetaPost struct{} func (n CustomMetaPost) GetID() string { diff --git a/jsonapi/marshal.go b/jsonapi/marshal.go index 891b5f9..2db7250 100644 --- a/jsonapi/marshal.go +++ b/jsonapi/marshal.go @@ -80,6 +80,13 @@ type MarshalCustomLinks interface { GetCustomLinks(string) Links } +// The MarshalMeta interface can be implemented if the struct should +// want any meta. +type MarshalMeta interface { + MarshalIdentifier + Meta() Meta +} + // The MarshalCustomRelationshipMeta interface can be implemented if the struct should // want a custom meta in a relationship. type MarshalCustomRelationshipMeta interface { @@ -254,6 +261,14 @@ func marshalData(element MarshalIdentifier, data *Data, information ServerInform } } + if casteMetaTarget, ok := element.(MarshalMeta); ok { + meta := casteMetaTarget.Meta() + data.Meta, err = json.Marshal(meta) + if err != nil { + return err + } + } + if references, ok := element.(MarshalLinkedRelations); ok { data.Relationships = getStructRelationships(references, information) } diff --git a/jsonapi/marshal_test.go b/jsonapi/marshal_test.go index fed3688..ddfaaa1 100644 --- a/jsonapi/marshal_test.go +++ b/jsonapi/marshal_test.go @@ -271,6 +271,22 @@ var _ = Describe("Marshalling", func() { }) }) + Context("When marshaling objects with data meta", func() { + It("contains the meta in the marshaled data object", func() { + post := CustomResourceMetaPost{} + i, err := Marshal(post) + Expect(err).To(BeNil()) + Expect(i).To(MatchJSON(`{ + "data": { + "type": "posts", + "id": "someID", + "attributes": {}, + "meta": { "access_count": 15 } + } + }`)) + }) + }) + Context("When marshaling compound objects", func() { It("marshals nested objects", func() { comment1 := Comment{ID: 1, Text: "First!", SubCommentsEmpty: true}