In my app, I have
defmodule MyWebApp.Endpoint do
use Phoenix.Endpoint, otp_app: :my_web_app
use Absinthe.Phoenix.Endpoint
which generates subscribe(), ubsubscribe(), broadcast!() etc functions with use
.
How can I inject behavior, e.g. logging or presence tracking, into these functions?
Also, subscribe/2
just gets topic
and opts
keyword list as arguments. Wouldn’t the topic name be generated/resolved in absinthe schema when we configure subscriptions to mutations, e.g.
object :lock_subscriptions do
field :lock_changed, non_null(:lock_result) do
arg(:lock_input, :lock_input)
config(fn
%{lock_input: %{id: target_id, target_type: target_type}}, _ ->
{:ok, topic: "#{@lock_changed_prefix}:#{target_type}:#{target_id}"}
_, _ ->
{:ok, topic: "#{@lock_changed_prefix}:*"}
end)
trigger([:acquire_lock, :release_lock],
topic: fn
%{success: true, id: target_id, target_type: target_type} ->
[
"#{@lock_changed_prefix}:#{target_type}:#{target_id}",
"#{@lock_changed_prefix}:*"
]
_ ->
"lock-changed-do-not-publish"
end
)
end
The subscribe
function,
@doc """
Subscribes the caller to the given topic.
See `Phoenix.PubSub.subscribe/3` for options.
"""
@callback subscribe(topic, opts :: Keyword.t) :: :ok | {:error, term}
doesn’t need to be aware of the users that subscribes, right? If I really wanted, I’d incorporate user id into topic name, e.g. “#{@lock_changed_prefix}:#{target_type}:#{target_id}:#{user.id}”. Maybe all it knows is process id, namely self()
.
BTW if the server dies and the supervisor restarts it, the PIDs will be all invalid, so how will PubSub know whom to notify?
Anyway, the main question is how to add behavior to these callbacks?
The use
macro generates something like
quote do
def subscribe(topic, opts \\ []) when is_binary(topic) do
Phoenix.PubSub.subscribe(pubsub_server!(), topic, opts)
end
How do I inject, for example, logging of arguments or adding topic to Phoenix.Tracker?