AshDispatch.Phoenix.UserChannel (AshDispatch v0.5.0)

View Source

Macro for creating a user channel with all AshDispatch functionality built-in.

Provides real-time updates for:

  • Notifications
  • Counter updates
  • Query invalidation

Usage

Create your channel with just 3 lines:

defmodule MyAppWeb.UserChannel do
  use AshDispatch.Phoenix.UserChannel,
    endpoint: MyAppWeb.Endpoint
end

Add to your socket:

channel "user:*", MyAppWeb.UserChannel

What You Get

  • join/3 - Authorizes and initializes channel
  • handle_info(:after_join, socket) - Sends initial counters/notifications
  • handle_in("refresh_counters", ...) - Client can request counter refresh
  • broadcast_notification/2 - Push notifications to user
  • broadcast_counter/4 - Push counter updates with metadata
  • broadcast_counters/2 - Push multiple counter updates

Configuration

The endpoint option is required. It's used for broadcasting.

use AshDispatch.Phoenix.UserChannel,
  endpoint: MyAppWeb.Endpoint

Customization

You can override any callback by defining it in your module:

defmodule MyAppWeb.UserChannel do
  use AshDispatch.Phoenix.UserChannel,
    endpoint: MyAppWeb.Endpoint

  # Custom join logic
  def join("user:" <> user_id, payload, socket) do
    # Your custom authorization
    if authorized?(socket, user_id) do
      send(self(), :after_join)
      {:ok, socket}
    else
      {:error, %{reason: "unauthorized"}}
    end
  end
end

Frontend Integration

Use the generated SDK hooks to connect:

import { useChannel } from '@/lib/ash-dispatch'

function App() {
  useChannel({
    channel: userChannel,
    onNotification: (notification) => {
      // Handle new notification
    }
  })
}