Want.Map (want v1.8.1)
Manages conversions to and from maps.
Link to this section Summary
Functions
Cast an incoming keyword list or map to an output map using the provided schema to control conversion rules and validations.
Link to this section Types
input()
Specs
key()
Specs
opts()
Specs
opts() :: Keyword.t()
result()
Specs
schema()
Specs
schema() :: map()
Link to this section Functions
cast(input, schema)
Specs
Cast an incoming keyword list or map to an output map using the provided schema to control conversion rules and validations.
Options
:merge
- Provide a map matching the given schema that contains default values to be used if the input value does not contain a particular field. Useful when updating a map with new inputs without overwriting all fields.
Examples
iex> Want.Map.cast(%{"id" => 1}, %{id: [type: :integer]}) {:ok, %{id: 1}}
iex> Want.Map.cast(%{}, %{id: [type: :integer, default: 1]}) {:ok, %{id: 1}}
iex> Want.Map.cast(%{"id" => "bananas"}, %{id: [type: :integer, default: 1]}) {:ok, %{id: 1}}
iex> Want.Map.cast(%{"hello" => "world", "foo" => "bar"}, %{hello: [], foo: [type: :atom]}) {:ok, %{hello: "world", foo: :bar}}
iex> Want.Map.cast(%{"date" => %Date{year: 2022, month: 01, day: 02}}, %{date: [type: :date]}) {:ok, %{date: %Date{year: 2022, month: 01, day: 02}}}
iex> Want.Map.cast(%{"date" => "2022-01-02"}, %{date: [type: :date]}) {:ok, %{date: %Date{year: 2022, month: 01, day: 02}}}
iex> Want.Map.cast(%{"hello" => "world"}, %{hello: [], foo: [required: true]})
iex> Want.Map.cast(%{"hello" => "world"}, %{hello: [type: :enum, valid: [:world]]}) {:ok, %{hello: :world}}
iex> Want.Map.cast(%{"hello" => "world"}, %{hello: [], foo: []}) {:ok, %{hello: "world"}}
iex> Want.Map.cast(%{"hello" => %{"foo" => "bar"}}, %{hello: %{foo: [type: :atom]}}) {:ok, %{hello: %{foo: :bar}}}
iex> Want.Map.cast(%{"id" => "bananas"}, %{id: [type: :integer, default: 1]}, merge: %{id: 2}) {:ok, %{id: 2}}