Exdantic.Type behaviour (exdantic v0.0.2)

View Source

Behaviour and macros for defining custom types.

This module provides the behaviour and utility functions for creating custom types in Exdantic schemas with validation and coercion capabilities.

Summary

Functions

Provides functionality for defining custom types in Exdantic schemas.

Types

coerce_function()

@type coerce_function() :: (term() -> {:ok, term()} | {:error, term()})

coerce_rule()

@type coerce_rule() :: coerce_function() | {module(), atom()} | nil

Callbacks

coerce_rule()

(optional)
@callback coerce_rule() :: coerce_rule()

custom_rules()

(optional)
@callback custom_rules() :: [atom()]

json_schema()

@callback json_schema() :: map()

type_definition()

@callback type_definition() :: Exdantic.Types.type_definition()

validate(term)

@callback validate(term()) :: {:ok, term()} | {:error, term()}

Functions

__using__(opts)

(macro)
@spec __using__(keyword()) :: Macro.t()

Provides functionality for defining custom types in Exdantic schemas.

When you use Exdantic.Type, your module gets:

  • The Exdantic.Type behaviour
  • Import of Exdantic.Types functions
  • Type aliases for coercion functions
  • A default implementation of validation with coercion support

Examples

defmodule MyApp.Types.Email do
  use Exdantic.Type

  def type_definition do
    {:type, :string, [format: ~r/^[^@]+@[^@]+.[^@]+$/]}
  end

  def json_schema do
    %{"type" => "string", "format" => "email"}
  end

  def validate(value) do
    case type_definition() |> Exdantic.Validator.validate(value) do
      {:ok, validated} -> {:ok, validated}
      {:error, _} -> {:error, "invalid email format"}
    end
  end
end