I’m persisting an enumerable for which a database transaction function is called on each element. The persistence function nicely returns {:ok | :error, any}, but I’m unclear about how I should handle this response at the level of the enumerable. If I have five elements, and any one of them fails, I want to be able to take some action. Is there a more idiomatic way of doing this than just iterating through the responses?
def load_enumerable(enum) do
enum
|> Enum.map(&load_element(&1))
|> Enum.find(fn {k, _v} -> k == :error end)
end
def load_element(element) do
Ecto.Multi.new()
|> Ecto.Multi.run(...)
|> Ecto.Multi.run(...)
|> Repo.transaction()
end
This is definitely a more efficient approach! I’m just curious if there was another approach altogether that I am missing.
I would think that anyone persisting large batches of data to a database would want a list of exceptions that need attention. Perhaps this is the way to go.