Current section

Files

Jump to
ecto_context lib ecto_context validate.ex
Raw

lib/ecto_context/validate.ex

defmodule EctoContext.Validate do
@moduledoc """
Validation helpers used by the EEx templates in `priv/templates/ecto_context/`.
These functions are called at runtime from code generated by `EctoContext`.
They guard against invalid options and unknown associations before
queries hit the database.
"""
@doc """
Validates that `assoc_atom` is a known association or `_id` field on `module`.
Raises `ArgumentError` if neither a `belongs_to` association nor a
corresponding `_id` field exists on the schema.
"""
@spec validate_assoc!(module(), atom()) :: :ok
def validate_assoc!(module, assoc_atom) do
has_association = not is_nil(module.__schema__(:association, assoc_atom))
has_field = :"#{assoc_atom}_id" in module.__schema__(:fields)
unless has_association or has_field do
raise ArgumentError, """
Invalid association. :#{assoc_atom} on #{module} does not exist.
Expected a belongs_to association or a :#{assoc_atom}_id field.
"""
end
end
@doc """
Validates that all keys in `opts` are in the `valid_keys` list.
Raises `ArgumentError` listing the unsupported keys if any are found.
"""
@spec validate_opts!(keyword(), [atom()]) :: :ok
def validate_opts!(opts, valid_keys) do
invalid_keys = Keyword.keys(opts) -- valid_keys
if Enum.any?(invalid_keys) do
raise ArgumentError, """
Unsupported option(s) found: #{Enum.map_join(invalid_keys, ", ", &":#{&1}")}.
Supported options are: #{Enum.map_join(valid_keys, ", ", &":#{&1}")}
"""
end
:ok
end
end