Skip to content

Commit ebb7923

Browse files
nstratosaren55555
authored andcommitted
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.
1 parent af3dab1 commit ebb7923

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

node.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ type ManyPayload struct {
2323
// Node is used to represent a generic JSON API Resource
2424
type Node struct {
2525
Type string `json:"type"`
26-
ID string `json:"id"`
26+
ID string `json:"id,omitempty"`
2727
ClientID string `json:"client-id,omitempty"`
2828
Attributes map[string]interface{} `json:"attributes,omitempty"`
2929
Relationships map[string]interface{} `json:"relationships,omitempty"`

response_test.go

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -196,6 +196,32 @@ func TestMarshalIDPtr(t *testing.T) {
196196
}
197197
}
198198

199+
func TestMarshalOnePayload_omitIDString(t *testing.T) {
200+
type Foo struct {
201+
ID string `jsonapi:"primary,foo"`
202+
Title string `jsonapi:"attr,title"`
203+
}
204+
205+
foo := &Foo{Title: "Foo"}
206+
out := bytes.NewBuffer(nil)
207+
if err := MarshalOnePayload(out, foo); err != nil {
208+
t.Fatal(err)
209+
}
210+
211+
var jsonData map[string]interface{}
212+
if err := json.Unmarshal(out.Bytes(), &jsonData); err != nil {
213+
t.Fatal(err)
214+
}
215+
payload := jsonData["data"].(map[string]interface{})
216+
217+
// Verify that empty ID of type string gets omitted. See:
218+
// https://github.com/google/jsonapi/issues/83#issuecomment-285611425
219+
_, ok := payload["id"]
220+
if ok {
221+
t.Fatal("Was expecting the data.id member to be omitted")
222+
}
223+
}
224+
199225
func TestMarshall_invalidIDType(t *testing.T) {
200226
type badIDStruct struct {
201227
ID *bool `jsonapi:"primary,cars"`

0 commit comments

Comments
 (0)