Hi
I want to broadcast every model change that happens in a controller to its corresponding channel.
For example I have
def index(conn, params = %{"app_id" => app_id, "conversation_id" => conversation_id}, user, _claims) do
page = Messenger.get_messages(user, conversation_id, params)
conn
|> Scrivener.Headers.paginate(page)
|> render("index.json", messages: page.entries)
end
def create(conn, params = %{"conversation_id" => conversation_id}, user, _claims) do
case Messenger.send_message(user, conversation_id, params) do
{:ok, %{message: message, conversation: conversation}} ->
payload = Phoenix.View.render(MessageView, "show.json", message: message)
MessageChannel.broadcast_add(conversation_id, payload)
conn
|> put_status(:created)
|> json(payload)
{:error, type, changeset, _} ->
conn
|> put_status(:unprocessable_entity)
|> render(ResendWeb.ChangesetView, "error.json", changeset: changeset)
end
end
Notice that I send the exact same response over the channel, as in the HTTP response.
With this approach I have to remember adding the appropriate channel broadcast function calls for every create
action.
I am curious to see if anybody has a smart way to abstract this out so that all post requests automatically broadcasts the result of an action to the corresponding channels