This is a package for easily adding a Postgres based pubsub system to your phoenix application.
If available in Hex, the package can be installed
by adding postgrex_pubsub
to your list of dependencies in mix.exs
:
def deps do
[
{:postgrex_pubsub, "~> 0.2.0"}
]
end
Documentation can be generated with ExDoc and published on HexDocs. Once published, the docs can be found at https://hexdocs.pm/postgrex_pubsub.
- Create an empy migration
mix ecto.gen.migration broadcast_users_mutation
- Use the
BroadcastMigration
macro
defmodule YourApp.Repo.Migrations.BroadcastUsersMutation do
use PostgrexPubsub.BroadcastPayloadMigration, table_name: "users"
end
- Migrate
mix ecto. migrate
defmodule YourApp.Listeners.Email do
use PostgrexPubsub.Listener, repo: YourApp.Repo
def handle_mutation_event(%{
"id" => row_id,
"new_row_data" => new_row_data,
"old_row_data" => old_row_data,
"table" => table,
"type" => type, # "INSERT", "UPDATE"
} = payload) do
IO.inspect(payload, label: "payload")
end
end
# application.ex
defmodule YourApp.Application do
use Application
def start(_type, _args) do
children = [
# ...
YourApp.Listeners.Email,
]
# ...
Supervisor.start_link(children, opts)
end
# ...
end
Now when inserting or updating a user you should see the following in your terminal
payload: %{
"id" => "b3e041a5-2d6e-4f6f-9afc-64f326d3227f",
"new_row_data" => %{
"email" => "[email protected]",
"id" => "b3e041a5-2d6e-4f6f-9afc-64f326d3227f",
"inserted_at" => "2020-03-30T19:40:17",
"name" => "Ben Church",
"stripe_customer_id" => "cus_H0USudjt8o4cuS",
"updated_at" => "2020-03-30T19:41:16"
},
"old_row_data" => %{
"email" => "[email protected]",
"id" => "b3e041a5-2d6e-4f6f-9afc-64f326d3227f",
"inserted_at" => "2020-03-30T19:40:17",
"name" => "Ben Church",
"updated_at" => "2020-03-30T19:40:17"
},
"table" => "users",
"type" => "UPDATE"
}
Usefull as pg_notify has a hard limit of 8000 bytes
- Create an empy migration
mix ecto.gen.migration broadcast_users_mutation
- Use the
BroadcastMigration
macro
defmodule YourApp.Repo.Migrations.BroadcastUsersMutation do
use PostgrexPubsub.BroadcastIdMigration, table_name: "users"
end
- Migrate
mix ecto. migrate
defmodule YourApp.Listeners.Email do
use PostgrexPubsub.Listener, repo: YourApp.Repo
def handle_mutation_event(%{
"id" => row_id,
"table" => table,
"type" => type, # "INSERT", "UPDATE"
} = payload) do
IO.inspect(row_id, label: "row_id")
end
end
# application.ex
defmodule YourApp.Application do
use Application
def start(_type, _args) do
children = [
# ...
YourApp.Listeners.Email,
]
# ...
Supervisor.start_link(children, opts)
end
# ...
end
Now when inserting or updating a user you should see the following in your terminal
row_id: %{
"id" => "b3e041a5-2d6e-4f6f-9afc-64f326d3227f",
"table" => "users",
"type" => "UPDATE"
}