Current section

Files

Jump to
manganese_entity_kit lib macros repo.ex
Raw

lib/macros/repo.ex

defmodule Manganese.EntityKit.Macros.Repo do
alias Manganese.CoreKit
alias Manganese.EntityKit.Structs
defmacro __using__(_) do
quote do
@doc """
Refresh all entities in an entities collection from the database.
"""
@spec reload_entities(Structs.EntitiesCollection.t) :: { :ok, Structs.EntitiesCollection.t } | { :error, CoreKit.Structs.APIError.t }
def reload_entities(entities_collection) do
Repo.transaction fn ->
%Structs.EntitiesCollection{
entities: Map.new(entities_collection.entities, fn
{ entity_type, nil } -> { entity_type, nil }
{ entity_type, entities_of_type } ->
{ entity_type, Map.new(entities_of_type, fn { id, entity } ->
entity_module = entity_type_to_module entity_type
entity =
case entity_module.find_by_id entity.id do
{ :ok, entity } -> entity
{ :error, api_error } -> rollback api_error
end
{ id, entity }
end) }
end)
}
end
end
@doc """
Refresh all entities in an entities collection from the database, raise on error.
"""
@spec reload_entities!(Structs.EntitiesCollection.t) :: Structs.EntitiesCollection.t
def reload_entities!(entities_collection) do
{ :ok, entities_collection } = reload_entities entities_collection
entities_collection
end
end
end
end