Current section
Files
Jump to
Current section
Files
lib/retort/meta.ex
defmodule Retort.Meta do
@moduledoc """
Ensures that the JSONAPI meta is correct for the environment
"""
# Functions
@doc """
Returns `meta` if it is valid for the environment; otherwise, raises an `ArgumentError`
"""
@spec valid!(
%{String.t => binary} | %{beam: binary} | map,
%{
required(:ecto_schema_modules) => [module, ...],
optional(:ecto_repo_module) => Ecto.Repo.t | nil
}
) :: map
def valid!(meta, options = %{ecto_schema_modules: ecto_schema_modules}) do
case Enum.filter(ecto_schema_modules, &database_backed?/1) do
[] ->
meta
database_backed_ecto_schema_modules ->
valid_with_database_backed_ecto_schema_modules!(meta, database_backed_ecto_schema_modules, options)
end
end
## Private Functions
defp database_backed?(ecto_schema_module), do: ecto_schema_module.__schema__(:source) != ""
defp valid_with_database_backed_ecto_schema_modules!(meta, database_backed_ecto_schema_modules, options) do
case Map.get(options, :ecto_repo_module) do
nil ->
raise ArgumentError,
"""
The `:ecto_repo_module` must be set to check if it is sandboxed when validating `meta` with database
backed Ecto.Schema modules (#{Enum.map_join(database_backed_ecto_schema_modules, ", ", &inspect/1)}).
"""
ecto_repo_module ->
valid_with_ecto_repo_module!(meta, ecto_repo_module)
end
end
defp valid_with_ecto_repo_module!(meta, ecto_repo_module) do
case ecto_repo_module.config()[:pool] do
Ecto.Adapters.SQL.Sandbox ->
valid_when_sandboxed!(meta, ecto_repo_module)
_ ->
meta
end
end
defp valid_when_sandboxed!(meta, ecto_repo_module) do
case meta do
# params from controllers
%{"beam" => beam} when is_binary(beam) ->
meta
# configuration to start_link
%{beam: beam} when is_binary(beam) ->
meta
_ ->
key = inspect(ecto_repo_module)
raise ArgumentError,
"""
When using `Ecto.Adapters.SQL.Sandbox` for the `config :my_app, #{key}, :pool`, you must set
`meta[:beam]` to the connection ownership information:
Retort.Meta.Beam.put(meta, #{key})
This cannot be done automatically because the calling process's pid will be the assumed owner process in
the meta data.
"""
end
end
end