View Source Want.Keyword (want v1.18.0)
Manages conversions to and from keyword lists.
Summary
Functions
Cast an incoming keyword list or map to an output keyword list using the provided schema to control conversion rules and validations.
Types
@type enumerable() :: Want.enumerable()
@type input() :: Want.enumerable()
@type opts() :: Keyword.t()
@type schema() :: map()
Functions
Cast an incoming keyword list or map to an output keyword list using the provided schema to control conversion rules and validations.
Examples
iex> Want.Keyword.cast(%{"id" => 1}, %{id: [type: :integer]})
{:ok, [id: 1]}
iex> Want.Keyword.cast(%{"archived" => "true"}, %{archived: [type: :boolean, default: false]})
{:ok, [archived: true]}
iex> Want.Keyword.cast(%{"archived" => "false"}, %{archived: [type: :boolean, default: false]})
{:ok, [archived: false]}
iex> Want.Keyword.cast(%{}, %{archived: [type: :boolean, default: false]})
{:ok, [archived: false]}
iex> Want.Keyword.cast(%{}, %{id: [type: :integer, default: 1]})
{:ok, [id: 1]}
iex> Want.Keyword.cast(%{"id" => "bananas"}, %{id: [type: :integer, default: 1]})
{:ok, [id: 1]}
iex> Want.Keyword.cast(%{"hello" => "world", "foo" => "bar"}, %{hello: [], foo: [type: :atom]})
{:ok, [hello: "world", foo: :bar]}
iex> Want.Keyword.cast(%{"hello" => "world"}, %{hello: [], foo: [required: true]})
{:error, "Failed to cast key foo (key :foo not found) and no default value provided."}
iex> Want.Map.cast(%{"datetime" => DateTime.from_unix!(0)}, %{datetime: [type: :datetime]})
{:ok, %{datetime: DateTime.from_unix!(0)}}
iex> Want.Map.cast(%{"datetime" => "1970-01-01T00:00:00Z"}, %{datetime: [type: :datetime]})
{:ok, %{datetime: DateTime.from_unix!(0)}}
iex> Want.Keyword.cast(%{"hello" => "world"}, %{hello: [], foo: []})
{:ok, [hello: "world"]}
iex> Want.Keyword.cast(%{"hello" => "world"}, %{hello: [type: :enum, valid: [:world]]})
{:ok, [hello: :world]}
iex> Want.Keyword.cast(%{"hello" => %{"foo" => "bar"}}, %{hello: %{foo: [type: :atom]}})
{:ok, [hello: [foo: :bar]]}
iex> Want.Keyword.cast(%{"id" => "bananas"}, %{id: [type: :integer, default: 1]}, merge: [id: 2])
{:ok, [id: 2]}
iex> Want.Keyword.cast(%{"id" => "bananas"}, %{id: [type: :any]})
{:ok, [id: "bananas"]}
iex> Want.Keyword.cast(%{"a" => %{"b" => %{"c" => 100}}}, %{id: [type: :integer, from: {"a", "b", "c"}]})
{:ok, [id: 100]}
iex> Want.Keyword.cast(%{"a" => [1, 2, 3, 4]}, %{a: [type: {:array, :integer}]})
{:ok, [a: [1, 2, 3, 4]]}
iex> Want.Keyword.cast(%{"a" => %{"b" => %{"c" => 100}}}, %{id: [type: :integer, from: {"a", "b", "c"}, transform: fn x -> x * 2 end]})
{:ok, [id: 200]}