ExParamsSchema.Type behaviour (ex_params_schema v0.1.1)

Copy Markdown View Source

Specifies how to use custom types as ExParamsSchema fields.

An adapter casts external input to a domain or primitive value, then converts that value to a JSON-compatible value for JSON Schema validation. ex_json_schema, rather than the adapter, validates standard constraints.

Implement typespec/0 to specify the generated params struct's field type as an AST. When it is not implemented, a struct adapter's t/0 is used; all other adapters use dynamic().

A minimal adapter implements the three required callbacks.

defmodule MyApp.TrimmedString do
  @behaviour ExParamsSchema.Type

  @impl true
  def cast(value, _options) when is_binary(value), do: {:ok, String.trim(value)}
  def cast(_value, _options), do: {:error, :not_a_string}

  @impl true
  def to_json(value, _options), do: value

  @impl true
  def json_schema(_options), do: %{"type" => "string"}

  @impl true
  def typespec, do: quote(do: String.t())
end

Specify {Module, adapter_options} as the field type. Specify field options outside the tuple.

field :slug, {MyApp.TrimmedString, []}, min_length: 1, error: :invalid_slug

Summary

Callbacks

Casts external input to an adapter value, returning {:error, detail} when casting fails.

Returns additional JSON Schema for an adapter value.

Converts an adapter value into a JSON-compatible value for JSON Schema validation.

Returns the AST representing the field type in the generated params struct.

Applies constraints specific to a cast adapter value.

Validates adapter-specific options provided in a field declaration.

Types

cast_result()

@type cast_result() :: {:ok, value :: term()} | {:error, detail :: term()}

json_array()

@type json_array() :: [json_value()]

json_object()

@type json_object() :: %{required(String.t()) => json_value()}

json_value()

@type json_value() ::
  boolean() | number() | String.t() | nil | json_array() | json_object()

Callbacks

cast(input, options)

@callback cast(input :: term(), options :: keyword()) :: cast_result()

Casts external input to an adapter value, returning {:error, detail} when casting fails.

json_schema(options)

@callback json_schema(options :: keyword()) :: map() | boolean()

Returns additional JSON Schema for an adapter value.

to_json(value, options)

@callback to_json(value :: term(), options :: keyword()) :: json_value()

Converts an adapter value into a JSON-compatible value for JSON Schema validation.

typespec()

(optional)
@callback typespec() :: Macro.t()

Returns the AST representing the field type in the generated params struct.

validate(value, options)

(optional)
@callback validate(value :: term(), options :: keyword()) ::
  :ok | {:error, detail :: term()}

Applies constraints specific to a cast adapter value.

validate_options(options)

(optional)
@callback validate_options(options :: keyword()) :: :ok | {:error, String.t()}

Validates adapter-specific options provided in a field declaration.