Raxol.Architecture.CQRS.Command behaviour (Raxol v2.0.1)

View Source

Base command module for CQRS pattern implementation in Raxol.

Commands represent write operations in the system and encapsulate the intent to perform an action. All commands should be immutable and contain all the data necessary to perform the operation.

Command Design Principles

  1. Intention Revealing: Command names should express business intent
  2. Immutable: Commands should be immutable once created
  3. Self-Contained: Commands should contain all necessary data
  4. Validated: Commands should validate their data upon creation
  5. Traceable: Commands should include metadata for auditing

Usage

defmodule MyApp.Commands.CreateUserCommand do
  use Raxol.Architecture.CQRS.Command

  defstruct [:user_id, :name, :email, :created_by, :metadata]

  @type t :: %__MODULE__{
    user_id: String.t(),
    name: String.t(),
    email: String.t(),
    created_by: String.t(),
    metadata: map()
  }

  def new(attrs) do
    %__MODULE__{
      user_id: attrs[:user_id] || UUID.uuid4(),
      name: attrs[:name],
      email: attrs[:email],
      created_by: attrs[:created_by],
      metadata: build_metadata(attrs)
    }
    |> validate()
  end

  defp validate(%__MODULE__{} = command) do
    with :ok <- validate_required(command, [:name, :email, :created_by]),
         :ok <- validate_email(command.email) do
      {:ok, command}
    else
      {:error, reason} -> {:error, reason}
    end
  end
end

Summary

Functions

Builds standard command metadata.

Extracts command type from a command struct.

Creates a command result structure.

Generates a unique command ID.

Generates a correlation ID for tracking related commands.

Validates email format.

Validates a field matches one of the allowed values.

Validates string length is within bounds.

Validates a field is within a specified range.

Validates required fields are present in the command.

Types

t()

@type t() :: struct()

Callbacks

new(attrs)

@callback new(attrs :: map()) :: {:ok, struct()} | {:error, term()}

Functions

build_metadata(attrs)

Builds standard command metadata.

command_type(map)

Extracts command type from a command struct.

create_result(command, status, data \\ nil, error \\ nil)

Creates a command result structure.

generate_command_id()

Generates a unique command ID.

generate_correlation_id()

Generates a correlation ID for tracking related commands.

validate_email(email)

Validates email format.

validate_inclusion(value, allowed_values)

Validates a field matches one of the allowed values.

validate_length(value, min, max)

Validates string length is within bounds.

validate_range(value, min, max)

Validates a field is within a specified range.

validate_required(command, required_fields)

Validates required fields are present in the command.