AshDispatch.Helpers.ChannelState (AshDispatch v0.5.1)

View Source

Helper for building initial Phoenix Channel state.

Combines counters and notifications into a single payload ready for Phoenix Channel's push/2. Loads data in parallel for performance.

Usage

alias AshDispatch.Helpers.ChannelState

# Build complete initial state
initial_state = ChannelState.build(user_id)
#=> %{"counters" => %{...}, "notifications" => [...]}

push(socket, "initial_state", initial_state)

Custom Options

# Limit notifications
ChannelState.build(user_id, notification_limit: 10)

# Load counters from specific domains
ChannelState.build(user_id, counter_domains: [MyApp.Orders])

# Custom notification serializer
ChannelState.build(user_id,
  notification_serializer: &MyApp.serialize_notification/1
)

Summary

Functions

Build complete initial state for a user.

Convert counter map to JSON-friendly format.

Functions

build(user_id, opts \\ [])

Build complete initial state for a user.

Loads counters and notifications in parallel for optimal performance.

Returns a map with:

  • "counters" - All counters as camelCase JSON (strings for JS)
  • "notifications" - Recent notifications

Options

  • :notification_limit - Number of recent notifications (default: 50)
  • :notification_serializer - Custom notification serializer function
  • :counter_domains - Specific Ash domains to load counters from
  • :parallel - Load in parallel (default: true)

Examples

# Standard usage
ChannelState.build("user-123")
#=> %{
#     "counters" => %{"pending_orders" => 5, "cart_items" => 3},
#     "notifications" => [%{id: "...", ...}, ...]
#   }

# With options
ChannelState.build("user-123",
  notification_limit: 10,
  counter_domains: [MyApp.Orders, MyApp.Tickets]
)

# Custom serializer
ChannelState.build("user-123",
  notification_serializer: &MyApp.serialize_notification/1
)

counters_to_json(counters)

Convert counter map to JSON-friendly format.

Converts atom keys to strings for JavaScript consumption.

Examples

ChannelState.counters_to_json(%{pending_orders: 5, cart_items: 3})
#=> %{"pending_orders" => 5, "cart_items" => 3}