Skip to content

Commit

Permalink
Add valitation to DELETE method
Browse files Browse the repository at this point in the history
  • Loading branch information
rfinochi committed May 15, 2020
1 parent 084e56c commit 450aba5
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 1 deletion.
5 changes: 4 additions & 1 deletion cmd/web/handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,10 @@ func (app *application) deleteItemEndpoint(c *gin.Context) {
}

err = app.itemModel.DeleteItem(id)
if err != nil {
if err == models.ErrNoRecord {
app.notFound(c.Writer)
return
} else if err != nil {
app.serverError(c.Writer, err)
return
}
Expand Down
1 change: 1 addition & 0 deletions cmd/web/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,7 @@ func TestValidations(t *testing.T) {
doError(app.router, t, "POST", "/api/", `{"id":8,"title":"Test_8","isdone":true}`, http.StatusConflict)
doError(app.router, t, "PUT", "/api/", `{"id":8,"title":"Test_8","isdone":true}`, http.StatusConflict)
doError(app.router, t, "PATCH", "/api/9", `{"id":9,"title":"Test_9","isdone":true}`, http.StatusNotFound)
doError(app.router, t, "DELETE", "/api/9", "", http.StatusNotFound)
}

func doAllAPIRequests(t *testing.T, a *application) {
Expand Down
6 changes: 6 additions & 0 deletions pkg/models/models.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,5 +76,11 @@ func (model ItemModel) UpdateItem(updatedItem Item) error {

// DeleteItem godoc
func (model ItemModel) DeleteItem(id int) error {
i, e := model.Repository.GetItem(id)

if i == (Item{}) && e == nil {
return ErrNoRecord
}

return model.Repository.DeleteItem(id)
}

0 comments on commit 450aba5

Please sign in to comment.