lib/roles/publisher.ex

defmodule Wampex.Roles.Publisher do
  @moduledoc """
  Handles requests and responses for Publishers
  """

  alias Wampex.Role
  @behaviour Role

  @publish 16
  @published 17

  defmodule Publish do
    @moduledoc false
    @enforce_keys [:topic]
    defstruct [:request_id, :topic, arg_list: [], arg_kw: %{}, options: %{}]

    @type t :: %__MODULE__{
            request_id: integer() | nil,
            topic: binary(),
            arg_list: list(any()),
            arg_kw: map(),
            options: map()
          }
  end

  @impl true
  def add(roles) do
    Map.put(roles, :publisher, %{})
  end

  @spec publish(Publish.t()) :: Wampex.message()
  def publish(%Publish{topic: t, options: opts, arg_list: al, arg_kw: akw}) do
    [@publish, opts, t, al, akw]
  end

  @impl true
  def handle([@published, request_id, id]) do
    {[{:next_event, :internal, :established}], request_id, {:ok, id}}
  end
end