Skip to content

Commit d8e0ec7

Browse files
authored
Return conflict error for incorrect id in PATCH (#298)
1 parent 9d550f3 commit d8e0ec7

File tree

2 files changed

+17
-2
lines changed

2 files changed

+17
-2
lines changed

api.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -699,6 +699,12 @@ func (res *resource) handleUpdate(c APIContexter, w http.ResponseWriter, r *http
699699
return NewHTTPError(nil, err.Error(), http.StatusNotAcceptable)
700700
}
701701

702+
identifiable, ok := updatingObj.Interface().(jsonapi.MarshalIdentifier)
703+
if !ok || identifiable.GetID() != id {
704+
conflictError := errors.New("id in the resource does not match servers endpoint")
705+
return NewHTTPError(conflictError, conflictError.Error(), http.StatusConflict)
706+
}
707+
702708
response, err := source.Update(updatingObj.Interface(), buildRequest(c, r))
703709

704710
if err != nil {

api_test.go

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -863,8 +863,8 @@ var _ = Describe("RestHandler", func() {
863863
Expect(err).To(BeNil())
864864
api.Handler().ServeHTTP(rec, req)
865865
// It's up to the user how to implement this. Api2go just checks if the type is correct
866-
Expect(rec.Code).To(Equal(http.StatusNotFound))
867-
Expect(string(rec.Body.Bytes())).To(MatchJSON(`{"errors":[{"status":"404","title":"post not found"}]}`))
866+
Expect(rec.Code).To(Equal(http.StatusConflict))
867+
Expect(string(rec.Body.Bytes())).To(MatchJSON(`{"errors":[{"status":"409","title":"id in the resource does not match servers endpoint"}]}`))
868868
})
869869

870870
It("POST without type returns 406", func() {
@@ -896,6 +896,15 @@ var _ = Describe("RestHandler", func() {
896896
Expect(target.Value).To(Equal(null.FloatFrom(2)))
897897
})
898898

899+
It("Update fails with incorrect id in payload", func() {
900+
reqBody := strings.NewReader(`{"data": {"id": "2", "attributes": {"title": "New Title"}, "type": "posts"}}`)
901+
req, err := http.NewRequest("PATCH", "/v1/posts/1", reqBody)
902+
Expect(err).To(BeNil())
903+
api.Handler().ServeHTTP(rec, req)
904+
Expect(rec.Code).To(Equal(http.StatusConflict))
905+
Expect(string(rec.Body.Bytes())).To(MatchJSON(`{"errors":[{"status":"409","title":"id in the resource does not match servers endpoint"}]}`))
906+
})
907+
899908
It("UPDATEs correctly using null.* values", func() {
900909
target := source.posts["1"]
901910
target.Value = null.FloatFrom(2)

0 commit comments

Comments
 (0)