Skip to content

Commit f049fd8

Browse files
committed
Example: Create user with chocolate relationship
1 parent d3dd640 commit f049fd8

File tree

2 files changed

+61
-2
lines changed

2 files changed

+61
-2
lines changed

examples/crud_example_test.go

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -176,6 +176,65 @@ var _ = Describe("CrudExample", func() {
176176
`))
177177
}
178178

179+
It("Creates a user with references chocolates", func() {
180+
createChocolate()
181+
182+
rec = httptest.NewRecorder()
183+
req, err := http.NewRequest("POST", "/v0/users", strings.NewReader(`
184+
{
185+
"data": {
186+
"type": "users",
187+
"attributes": {
188+
"user-name": "marvin"
189+
},
190+
"relationships": {
191+
"sweets": {
192+
"data": [
193+
{
194+
"id": "1",
195+
"type": "chocolates"
196+
}
197+
]
198+
}
199+
}
200+
}
201+
}
202+
`))
203+
Expect(err).ToNot(HaveOccurred())
204+
api.Handler().ServeHTTP(rec, req)
205+
Expect(rec.Code).To(Equal(http.StatusCreated))
206+
Expect(rec.Body.String()).To(MatchJSON(`
207+
{
208+
"meta": {
209+
"author": "The api2go examples crew",
210+
"license": "wtfpl",
211+
"license-url": "http://www.wtfpl.net"
212+
},
213+
"data": {
214+
"id": "1",
215+
"type": "users",
216+
"attributes": {
217+
"user-name": "marvin"
218+
},
219+
"relationships": {
220+
"sweets": {
221+
"data": [
222+
{
223+
"id": "1",
224+
"type": "chocolates"
225+
}
226+
],
227+
"links": {
228+
"related": "http://localhost:31415/v0/users/1/sweets",
229+
"self": "http://localhost:31415/v0/users/1/relationships/sweets"
230+
}
231+
}
232+
}
233+
}
234+
}
235+
`))
236+
})
237+
179238
It("Replaces users sweets", func() {
180239
createUser()
181240
createChocolate()

examples/model/model_user.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -41,9 +41,9 @@ func (u User) GetReferences() []jsonapi.Reference {
4141
// GetReferencedIDs to satisfy the jsonapi.MarshalLinkedRelations interface
4242
func (u User) GetReferencedIDs() []jsonapi.ReferenceID {
4343
result := []jsonapi.ReferenceID{}
44-
for _, chocolate := range u.Chocolates {
44+
for _, chocolateID := range u.ChocolatesIDs {
4545
result = append(result, jsonapi.ReferenceID{
46-
ID: chocolate.ID,
46+
ID: chocolateID,
4747
Type: "chocolates",
4848
Name: "sweets",
4949
})

0 commit comments

Comments
 (0)