CastParams.Type behaviour (CastParams v0.0.6)

View Source

Define casting types

Summary

Types

Custom types are represented by user-defined modules.

Primitive types.

t()

A type, primitive or custom.

Callbacks

Casts the given input to the custom type.

Returns the type name for the custom type.

Functions

Casts the given input to the custom type.

Types

custom()

@type custom() :: atom()

Custom types are represented by user-defined modules.

primitive()

@type primitive() :: base() | composite()

Primitive types.

t()

@type t() :: primitive() | custom()

A type, primitive or custom.

Callbacks

cast(value)

@callback cast(value :: term()) ::
  {:ok, casted_value :: term()} | {:error, reason :: term()}

Casts the given input to the custom type.

type()

@callback type() :: t()

Returns the type name for the custom type.

Functions

cast(type, value)

@spec cast(t(), term()) :: {:ok, term()} | {:error, term()}

Casts the given input to the custom type.

Basic types

[:boolean, :integer, :string, :float, :decimal, :date, :time, :naive_datetime, :utc_datetime]

Example

iex> cast(:integer, "1.0")
{:ok, 1}
iex> cast(:integer, "")
{:error, :invalid}

iex> cast(:string, "some string")
{:ok, "some string"}
iex> cast(:string, nil)
{:ok, ""}

iex> cast(:integer, "1")
{:ok, 1}
iex> cast(:integer, "1.0")
{:ok, 1}

iex> cast(:boolean, "1")
{:ok, true}
iex> cast(:boolean, "0")
{:ok, false}

iex> cast(:float, "1")
{:ok, 1.0}
iex> cast(:float, "1.0")
{:ok, 1.0}

iex> cast(:decimal, "1.001")
{:ok, Decimal.new("1.001")}

iex> cast(:date, "2024-01-15")
{:ok, ~D[2024-01-15]}

iex> cast(:time, "12:34:56")
{:ok, ~T[12:34:56]}

iex> cast(:naive_datetime, "2024-01-15T12:34:56")
{:ok, ~N[2024-01-15 12:34:56]}

iex> cast(:utc_datetime, "2024-01-15T12:34:56Z")
{:ok, ~U[2024-01-15 12:34:56Z]}

primitive_types()