Add omitempty to Node.ID (#89)

This commit adds omitempty to the field ID of type Node. This is needed
when constructing an entity client-side and sending it to the server for
creation. Without omitempty, the constructed entity will contain an
empty "id": "", which is not sensible to transmit.

This change addresses #83.
This commit is contained in:
Stratos Neiros 2017-05-24 06:17:04 +03:00 committed by Aren Patel
parent af3dab1a94
commit ebb7923313
2 changed files with 27 additions and 1 deletions

View File

@ -23,7 +23,7 @@ type ManyPayload struct {
// Node is used to represent a generic JSON API Resource
type Node struct {
Type string `json:"type"`
ID string `json:"id"`
ID string `json:"id,omitempty"`
ClientID string `json:"client-id,omitempty"`
Attributes map[string]interface{} `json:"attributes,omitempty"`
Relationships map[string]interface{} `json:"relationships,omitempty"`

View File

@ -196,6 +196,32 @@ func TestMarshalIDPtr(t *testing.T) {
}
}
func TestMarshalOnePayload_omitIDString(t *testing.T) {
type Foo struct {
ID string `jsonapi:"primary,foo"`
Title string `jsonapi:"attr,title"`
}
foo := &Foo{Title: "Foo"}
out := bytes.NewBuffer(nil)
if err := MarshalOnePayload(out, foo); err != nil {
t.Fatal(err)
}
var jsonData map[string]interface{}
if err := json.Unmarshal(out.Bytes(), &jsonData); err != nil {
t.Fatal(err)
}
payload := jsonData["data"].(map[string]interface{})
// Verify that empty ID of type string gets omitted. See:
// https://github.com/google/jsonapi/issues/83#issuecomment-285611425
_, ok := payload["id"]
if ok {
t.Fatal("Was expecting the data.id member to be omitted")
}
}
func TestMarshall_invalidIDType(t *testing.T) {
type badIDStruct struct {
ID *bool `jsonapi:"primary,cars"`