From 704bf7ba0f735238583644da9daf2574407a2faf Mon Sep 17 00:00:00 2001 From: Ben Wilson Date: Mon, 27 Jan 2020 18:49:15 -0500 Subject: [PATCH 1/2] more flexible functions --- lib/fable/events.ex | 30 +++++++++++++++++++++++------- 1 file changed, 23 insertions(+), 7 deletions(-) diff --git a/lib/fable/events.ex b/lib/fable/events.ex index 77c1071..9901620 100644 --- a/lib/fable/events.ex +++ b/lib/fable/events.ex @@ -239,18 +239,35 @@ defmodule Fable.Events do Keyword.t() ) :: transation_fun - def emit(config, %{__meta__: %Ecto.Schema.Metadata{}} = aggregate, fun, changes \\ %{}, opts) - when is_function(fun, 3) do + def emit(config, %{__meta__: %Ecto.Schema.Metadata{}} = aggregate, fun, changes \\ %{}, opts) do check_schema_fields(aggregate) fn -> aggregate = lock(aggregate, config.repo) || aggregate - events = fun.(aggregate, config.repo, changes) - result_of_applied_events = handle_events(config, aggregate, events, opts) - rollback_on_error(config.repo, result_of_applied_events) + + case call_fun(fun, aggregate, config, changes) do + {:error, reason} -> + config.repo.rollback(reason) + + events -> + result_of_applied_events = handle_events(config, aggregate, events, opts) + rollback_on_error(config.repo, result_of_applied_events) + end end end + defp call_fun(fun, aggregate, _config, _changes) when is_function(fun, 1) do + fun.(aggregate) + end + + defp call_fun(fun, aggregate, config, _changes) when is_function(fun, 2) do + fun.(aggregate, config.repo) + end + + defp call_fun(fun, aggregate, config, changes) when is_function(fun, 3) do + fun.(aggregate, config.repo, changes) + end + @doc false @spec emit( Fable.Config.t(), @@ -261,8 +278,7 @@ defmodule Fable.Events do Keyword.t() ) :: Ecto.Multi.t() - def emit(%{repo: repo} = config, %Ecto.Multi{} = multi, aggregate, name, fun, opts) - when is_function(fun, 3) do + def emit(%{repo: repo} = config, %Ecto.Multi{} = multi, aggregate, name, fun, opts) do Ecto.Multi.run(multi, name, fn ^repo, changes -> emit(config, aggregate, fun, changes, opts) |> repo.transaction() From 05ff805221bafbc1ae662e2bdf59066d9e6f3123 Mon Sep 17 00:00:00 2001 From: Ben Wilson Date: Tue, 28 Jan 2020 09:52:43 -0500 Subject: [PATCH 2/2] require at least 2 arity function --- lib/fable/events.ex | 4 ---- 1 file changed, 4 deletions(-) diff --git a/lib/fable/events.ex b/lib/fable/events.ex index 9901620..b73771f 100644 --- a/lib/fable/events.ex +++ b/lib/fable/events.ex @@ -256,10 +256,6 @@ defmodule Fable.Events do end end - defp call_fun(fun, aggregate, _config, _changes) when is_function(fun, 1) do - fun.(aggregate) - end - defp call_fun(fun, aggregate, config, _changes) when is_function(fun, 2) do fun.(aggregate, config.repo) end