Create different pub_sub topics if field is set

I have a resource that I want to send notifications via pub_sub when a new one is created.

In this resource, I have a relationship with my User resource:

    belongs_to :user, Core.Marketplace.Accounts.User do
      allow_nil? true
      public? true
    end

Here is how the pub_sub part is configured:

  pub_sub do
    module Phoenix.PubSub
    name Core.PubSub

    prefix "notifications"

    publish :create, ["new", [:user_id, nil]]
  end

What I want to achieve is that, if the user_id field is non-nil when create is called, I want a notification with the topic: notifications:new:<user_id> and, when the user_id field is nil, I want a notification with the topic: notifications:new.

The issue I’m having is that, with my current pub_sub config, Both topics will be generated if created is called with a user_id.

Is there some good way to achieve that with the pub_sub DSL?

Found a solution right after posting.. you can setup a filter with the publish DSL, so I changed my pub_sub to this:

publish :create, ["new", :user_id], filter: fn %{data: data} -> not is_nil(data.user_id) end

publish :create, ["new", nil], filter:   fn %{data: data} -> is_nil(data.user_id) end
1 Like