extreme_system v0.2.0 Extreme.System.GenAggregate

Generic Aggregate module.

Example

defmodule MyAggregate do
  use Extreme.System.GenAggregate

  defmodule State, do: defstruct GenAggregate.state_params ++ [:msg]

  ## Client API

  def start_link(ttl \ 2_000), do: GenAggregate.start_link __MODULE__, ttl

  def do_something(pid, val), do: exec pid, {:do_something, val}

  def message(pid), do: exec pid, :get_message

  ## Server Callbacks

  def init(ttl) do
    state = initial_state(ttl)
              |> Map.put(:msg, "")
    {:ok, struct(State, state)}
  end

  def handle_exec({:do_something, val}, from, state) do
    events = [%{val: val}]
    result = {:ok, state.transaction, events}

    {:block, from, result, %{state | events: events}}
  end
  def handle_exec(:get_message, from, state) do
    {:noblock, from, state.msg, state}
  end

  defp apply_events([%{val: val} | tail], state) do
    state = %{ state | msg: state.msg <> val }
    apply_events tail, state
  end
end

Use it then as: {:ok, a} = MyAggregate.start_link {:ok, transaction_id, _events, version, _response} = MyAggregate.do_something(a, “something”) {:ok, _new_state} = MyAggregate.commit a, transaction_id MyAggregate.message(a) #=> “something”

Summary

Functions

handle_cmd(cmd, fun) (macro)
handle_cmd(cmd, params, metadata \\ [], fun) (macro)
start_link(module, init_values, options \\ [])
state_params()