AshCommanded.Commanded.ParameterTransformer (AshCommanded v0.1.0)
View SourceAdvanced parameter transformation for mapping commands to Ash actions.
This module provides a more sophisticated approach to parameter transformation than the basic mapping in CommandActionMapper. It allows for:
- Type conversion and validation
- Default values
- Computed fields
- Nested transformations
- Collection handling
- Custom transformation functions
These transformations can be defined in the DSL and are used when mapping commands to Ash actions.
Example
defmodule MyApp.User do
use Ash.Resource,
extensions: [AshCommanded.Commanded.Dsl]
commanded do
commands do
command :register_user do
fields [:id, :name, :email, :birthdate, :roles]
transform_params do
# Simple field rename
map :name, to: :full_name
# Type conversion
cast :birthdate, :date
# Computed field
compute :age, fn params ->
date = params.birthdate
now = Date.utc_today()
years = now.year - date.year
if Date.compare(
%{date | year: now.year},
%{now | month: date.month, day: date.day}
) == :gt, do: years - 1, else: years
end
# Nested transformation for collections
transform :roles, fn roles ->
roles |> Enum.map(&String.to_atom/1)
end
# Add default values
default :status, "active"
default :registered_at, &DateTime.utc_now/0
# Custom transformation function
custom fn params ->
Map.put(params, :normalized_email, String.downcase(params.email))
end
end
end
end
end
end
Summary
Functions
Builds a transformation specification from a DSL block.
Apply a transformation specification to command parameters.
Functions
Builds a transformation specification from a DSL block.
This function is used by the DSL to convert transformation declarations into a list of transformation specifications that can be applied to command parameters.
Parameters
transform_block
- A keyword list of transformation declarations
Returns
A list of transformation specifications.
Example
build_transforms([
map: [:name, to: :full_name],
cast: [:birthdate, :date],
compute: [:age, fn params -> calculate_age(params.birthdate) end],
default: [:status, "active"]
])
Apply a transformation specification to command parameters.
Takes a map of parameters from a command and a transformation spec, and returns a new map with the transformations applied.
Parameters
params
- Map of parameters from the commandtransforms
- List of transformation specifications
Returns
A new map with all transformations applied.
Example
transform_params(
%{name: "John Doe", email: "john@example.com"},
[
{:map, :name, [to: :full_name]},
{:compute, :display_name, [using: fn p -> "Display name" end]},
{:default, :created_at, [value: DateTime.utc_now()]}
]
)