Last active
August 29, 2015 14:01
-
-
Save mathiasverraes/285cd3e5996b214184e8 to your computer and use it in GitHub Desktop.
event sourced aggregate
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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}] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-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. | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Update: used foldl instead of recursion