AshCommanded.Commanded.Middleware.BaseMiddleware (AshCommanded v0.1.0)
View SourceBase module for implementing command middleware in AshCommanded.
This module provides default implementations and helper functions for common middleware patterns. By using this module, you can implement only the callbacks you need while inheriting sensible defaults.
Examples
defmodule MyApp.LoggingMiddleware do
use AshCommanded.Commanded.Middleware.BaseMiddleware
@impl true
def before_dispatch(command, context, next) do
# Log command being dispatched
IO.inspect(command, label: "Dispatching command")
next.(command, context)
end
@impl true
def after_dispatch({:ok, result} = success, command, _context) do
# Log successful execution
IO.inspect(result, label: "Command succeeded")
success
end
def after_dispatch({:error, reason} = error, command, _context) do
# Log failed execution
IO.inspect(reason, label: "Command failed")
error
end
end
Default Implementations
By default, this module:
- Passes the command and context unchanged to the next middleware
- Returns the result from the command handler unchanged
Summary
Functions
Using this module will implement the CommandMiddleware behavior.
Helper to apply a list of middleware to a command.
Functions
Using this module will implement the CommandMiddleware behavior.
@spec apply_middleware( middleware :: [module()], command :: struct(), context :: map(), final_handler :: (struct(), map() -> {:ok, any()} | {:error, any()}) ) :: {:ok, any()} | {:error, any()}
Helper to apply a list of middleware to a command.
Parameters
middleware
- List of middleware modules to applycommand
- The command to processcontext
- The context for the commandfinal_handler
- Function to call after all middleware has been applied
Examples
apply_middleware(
[LoggingMiddleware, ValidationMiddleware],
%MyCommand{},
%{},
fn cmd, ctx -> {:ok, dispatch_command(cmd)} end
)