Skip to content

Instantly share code, notes, and snippets.

@mathiasverraes
Last active August 29, 2015 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mathiasverraes/285cd3e5996b214184e8 to your computer and use it in GitHub Desktop.
Save mathiasverraes/285cd3e5996b214184e8 to your computer and use it in GitHub Desktop.
event sourced aggregate
c(order).
History1 = order:add_orderline([], 15).
History2 = order:add_orderline(History1, 50).
History3 = order:pay_for_order(History2, 20).
% ** exception throw: {payment_amount_is_too_small,{price,65}}
History3 = order:pay_for_order(History2, 65).
History3.
% [{orderline_was_added,15}, {orderline_was_added,50}, {order_was_paid,65}]
-module(order).
-export([add_orderline/2, pay_for_order/2]).
-import(lists, [foldl/3]).
% Command methods
add_orderline(History, Price)
-> History ++ [{orderline_was_added, Price}].
pay_for_order(History, Amount)
-> guard_payment_amount(History, Amount),
History ++ [{order_was_paid, Amount}].
% Guards
guard_payment_amount(Events, Amount) ->
Price = project_order_price(Events),
case Amount < Price of
true -> throw({payment_amount_is_too_small, {price, Price}});
false -> ignore
end.
% Calculate state
% Only react to orderline_was_added events, ignore everything else
project_order_price(Events)
-> lists:foldl(project_order_price, 0, Events).
project_order_price({orderline_was_added, Price}, Total) -> Total + Price;
project_order_price(_, Total) -> Total.
@mathiasverraes
Copy link
Author

Update: used foldl instead of recursion

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment