How do I extend Ecto.Repo to broadcast changes to pubsub?

65 Views Asked by At

I'm trying to get my app's Repo to broadcast inserts on a phoenix channel, but I'm not sure about the right way to extend Ecto.Repo. I've tried this, but I'm getting compilation, and it doesn't like the right strategy either. What should I be doing here?

defmodule Mars.Repo do
  require Logger

  use Ecto.Repo,
    otp_app: :mars,
    adapter: Ecto.Adapters.Postgres

  def insert(x, opts) do
    with {:ok, result} <- Ecto.Repo.insert(x, opts) do
      broadcast(result)
      {:ok, result}
    else
      e -> e
    end
  end

end

Current working solution:

  def insert_cast(x, opts \\ []), do: action_cast(&Repo.insert/2, x, opts)
  def transaction_cast(x, opts \\ []), do: action_cast(&Repo.transaction/2, x, opts)

  defp action_cast(action, x, opts \\ []) do
    with {:ok, result} <- action.(x, opts) do
      try do
        broadcast(result)
      rescue
        e ->
          Logger.warn("#{__MODULE__} could not broadcast for #{inspect(x)}")
          {:ok, result}
      end

      {:ok, result}
    else
      e -> e
    end
  end
0

There are 0 best solutions below