AshDispatch.Event.Helpers (AshDispatch v0.5.0)

View Source

Helper functions for events that use Ash introspection to derive behavior.

These helpers enable zero-configuration recipient resolution by:

  • Introspecting Ash resources to find user relationships
  • Querying configured User module for admins
  • Extracting users from context automatically

Configuration Required

In your application config:

config :ash_dispatch,
  user_module: MyApp.Accounts.User,
  admin_filter: [super_admin: true]

How It Works

For :admin audience:

  • Queries user_module with admin_filter
  • Returns list of admin users

For :user audience:

  • Extracts user from context using Ash introspection
  • Follows relationships defined in resources
  • No hardcoded patterns needed

For :system audience:

  • Returns configured system recipients (if any)

Summary

Functions

Evaluates an Ash filter expression against a user.

Extracts the target user (recipient) from context and channel.

Resolves recipients for a channel based on its audience.

Functions

evaluate_user_filter(user, filter)

Evaluates an Ash filter expression against a user.

Uses the Ash query engine to properly evaluate filter expressions, supporting all Ash filter syntax (nested fields, temporal expressions, etc.).

Examples

# Simple filter
evaluate_user_filter(user, [confirmed_at: nil])
#=> true/false

# Complex filter
evaluate_user_filter(user, [admin: true, archived: false])
#=> true/false

Returns true if user matches the filter, false otherwise.

extract_target_user(context, channel)

Extracts the target user (recipient) from context and channel.

Used by should_send?/2 to determine the recipient for filter evaluation.

Returns the user struct if found, nil otherwise.

resolve_recipients_for_audience(context, channel, event_config \\ %{})

Resolves recipients for a channel based on its audience.

Uses Ash introspection to automatically find and extract users. Supports both legacy hardcoded audiences and new filter-based config.

Filter-Based Resolution (New)

Configure filters per audience in config:

config :ash_dispatch,
  recipient_filters: [
    audiences: [
      admin: [admin: true],
      user: [],
      support: [role: :support]
    ]
  ]

Or override per-event in DSL:

event :urgent,
  recipient_filter: [
    audiences: [admin: [admin: true, on_duty: true]]
  ]

Examples

# Admin audience - uses filter from config
resolve_recipients_for_audience(context, %Channel{audience: :admin})
# => [%{id: "1", email: "admin@example.com", display_name: "Admin"}]

# User audience - extracts from context via Ash
resolve_recipients_for_audience(context, %Channel{audience: :user})
# => [%{id: "123", email: "user@example.com", display_name: "John"}]