Lapis.Schema (Lapis v0.2.0)
The main building block of Lapis.
Schema consists of:
- Parser: a fallible function that transforms input into output
- Reverser: a function that transforms output back to its input (not strictly)
- Refinements: a set of post-parse validations
- Assigns: key-value metadata available to parsers, validators, and refinements
Summary
Functions
Assign key-value entries to the schema.
Assign a key-value entry to the schema.
Create a new schema.
Parse input with the schema.
Append a refine to the schema.
Reverse data with the schema.
Functions
Assign key-value entries to the schema.
This is the same as calling assign/3 with individual key-value pairs, but allows
any enumerable that emits {key, value}.
iex> schema =
...> Lapis.Schema.new(&Function.identity/1)
...> |> Lapis.Schema.assign(foo: :foo, bar: :bar)
...> |> Lapis.Schema.assign(baz: "baz")
iex> schema.assigns
%{foo: :foo, bar: :bar, baz: "baz"}
Assign a key-value entry to the schema.
Assigns allow storing any metadata in the schema. Assigns are available as the second argument to parsers and reversers.
iex> schema =
...> Lapis.Schema.new(fn x, %{tag: tag} -> {:ok, {tag, x}} end)
...> |> Lapis.Schema.assign(schema, tag: :foo)
iex> Lapis.parse(schema, "data")
{:ok, {:foo, "data"}}Assigns are the primary way to enable generic parsers/reversers without closures, which in turn enables function reusability and compile-time schemas.
TODO: example of "nil or value" bidirectional schema.
Refinements have their own assigns.
Create a new schema.
Parse is a function that accepts either input or input, schema. Parse is expected to return:
{:ok, value}or just anyvaluefor success.{:error, reason}for failure.reasonmay beLapis.Error, or anything else that will be passed toLapis.Error.new/1.
Note: Lapis.Schema.parse/2 normalizes the output and always returns {:ok, value} or {:error, %Lapis.Error{}}.
Reverse is a function that accepts either output or output, schema. Reverse, ideally, transforms the output back to its input, but this is up to implementor.
Default reverse simply returns its input.
Parse input with the schema.
Always returns {:ok, value} or {:error, %Lapis.Error{}}.
Re-exported as Lapis.parse/2.
iex> Lapis.Schema.new(fn _ -> {:ok, "value"} end) |> Lapis.parse()
{:ok, "value"}
iex> Lapis.Schema.new(fn _ -> "value" end) |> Lapis.parse()
{:ok, "value"}
iex> {:error, %Lapis.Error{} = err} =
...> Lapis.Schema.new(fn _ -> {:error, :very_bad} end)
...> |> Lapis.parse()
iex> {:error, %Lapis.Error{} = err2} =
...> Lapis.Schema.new(fn _ -> {:error, Lapis.Error.new(:very_bad)} end)
...> |> Lapis.parse()
iex> err1 === err2
true
Append a refine to the schema.
Reverse data with the schema.