vt-elixir / ja_resource

A behaviour to reduce boilerplate code in your JSON-API compliant Phoenix controllers without sacrificing flexibility.
Other
113 stars 33 forks source link

Use a changeset when handling delete requests #69

Closed swelham closed 6 years ago

swelham commented 7 years ago

Currently I am having to workaround an issue where constraint errors are not being caught for delete requests and therefore returning a 500 status code instead of a 422.

For example, say I have a post schema with comments, I only want to be able to delete a post if there are no linked comments. To ensure this I am using a no_assoc_constraint in my changeset, however ja_resource currently calls Repo.delete directly on the model and not via a changeset.

At the moment I am having to implement the following in my controller to get the correct behaviour on my api.

def handle_delete(_conn, post) do
  post
  |> Post.changeset
  |> Repo.delete
  |> respond
 end

def respond({:error, errors}), do: {:errors, errors}
def respond(result), do: result

Note the atom change of :error to :errors required to get JaResource.Delete.respond to correctly match the response.