JSV.Helpers.OptsValidator (jsv v0.20.0)

Copy Markdown View Source

Validation helper for JSV public API options.

Summary

Functions

Raises an ArgumentError describing an option whose value did not pass validation. expected is a human description such as "a boolean".

Raises an ArgumentError describing an unknown option key.

Validates opts against fun, accumulating values into the defaults map and returning the merged map.

Types

key()

@type key() :: atom()

validator()

@type validator() :: (key(), term() -> term())

Functions

invalid_option!(key, value, expected)

@spec invalid_option!(key(), term(), String.t()) :: no_return()

Raises an ArgumentError describing an option whose value did not pass validation. expected is a human description such as "a boolean".

iex> JSV.Helpers.OptsValidator.invalid_option!(:cast, "yes", "a boolean")
** (ArgumentError) invalid value for option :cast, expected a boolean, got: "yes"

unknown_option!(key)

@spec unknown_option!(key()) :: no_return()

Raises an ArgumentError describing an unknown option key.

iex> JSV.Helpers.OptsValidator.unknown_option!(:bogus)
** (ArgumentError) unknown option :bogus

validate(opts, defaults, fun)

@spec validate(keyword(), map(), validator()) :: map()

Validates opts against fun, accumulating values into the defaults map and returning the merged map.

The validator is called as fun.(key, value) and must return the value to store. Invalid options should raise (see invalid_option!/3 and unknown_option!/1).

iex> JSV.Helpers.OptsValidator.validate([a: 1, b: 2], %{}, fn _key, value -> value*2 end)
%{a: 2, b: 4}

iex> JSV.Helpers.OptsValidator.validate([cast: false], %{cast: true}, fn _key, value -> value end)
%{cast: false}

iex> JSV.Helpers.OptsValidator.validate([{:cast, :hello}], %{}, fn key, value ->
...>   JSV.Helpers.OptsValidator.invalid_option!(key, value, "a boolean")
...> end)
** (ArgumentError) invalid value for option :cast, expected a boolean, got: :hello

iex> JSV.Helpers.OptsValidator.validate([:foo], %{cast: true}, fn _key, value -> value end)
** (ArgumentError) expected a {key, value} option tuple, got: :foo