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

Hook for created / updated #41

Closed topaxi closed 7 years ago

topaxi commented 7 years ago

I want to publish changes to a record on a phoenix channel. Currently only hooks exist before ja_resource persists data, therefore I don't know if it succeeded. I think created, updated and deleted hooks might be needed for this? Or how should I currently solve this?

alanpeabody commented 7 years ago

@topaxi I would look at a "service" module or similar. JaResource is really just about the API interface, your business logic should live somewhere more reusable and better defined. A service example:

defmodule CommentController do
  use MyApp.Web, :controller
  plug JaResource

  def handle_create(conn, attributes) do
    CommentService.create_comment(attributes)
  end
end

defmodule CommentService do

  def create_comment(attributes) do
    cast(%Comment{}, attributes, [:body])
    |> #validate etc
    |> Repo.insert
    |> case do
      {:ok, comment} -> sync_to_socket(comment) #this just needs to return {:ok, comment} after syncing
      other -> other # errors are passed along and rendered appropriately.
    end
  end
end
topaxi commented 7 years ago

Alright, so returning a non-changeset from a handle_create / handle_update function does not trigger the default ja_resource insertion/update logic? Then this is exactly what I was looking for 👍

topaxi commented 7 years ago

Works, thanks a lot! :)