Anvil.Schema (Anvil v0.1.1)

View Source

Defines the structure and validation rules for labels.

Schemas are domain-agnostic and support various field types for diverse annotation tasks.

Summary

Functions

Returns the field with the given name, or nil if not found.

Creates a new schema with the given options.

Returns all optional field names.

Returns all required field names.

Validates a map of values against the schema.

Types

t()

@type t() :: %Anvil.Schema{
  fields: [Anvil.Schema.Field.t()],
  metadata: map(),
  name: String.t(),
  version: String.t()
}

Functions

get_field(schema, name)

@spec get_field(t(), String.t()) :: Anvil.Schema.Field.t() | nil

Returns the field with the given name, or nil if not found.

new(opts)

@spec new(keyword()) :: t()

Creates a new schema with the given options.

Examples

iex> schema = Anvil.Schema.new(
...>   name: "sentiment",
...>   fields: [
...>     %Anvil.Schema.Field{
...>       name: "score",
...>       type: :range,
...>       required: true,
...>       min: 1,
...>       max: 5
...>     }
...>   ]
...> )
iex> schema.name
"sentiment"

optional_fields(schema)

@spec optional_fields(t()) :: [String.t()]

Returns all optional field names.

required_fields(schema)

@spec required_fields(t()) :: [String.t()]

Returns all required field names.

validate(schema, values)

@spec validate(t(), map()) :: {:ok, map()} | {:error, [map()]}

Validates a map of values against the schema.

Returns {:ok, values} if valid, or {:error, errors} with a list of validation errors.

Examples

iex> schema = Anvil.Schema.new(
...>   name: "test",
...>   fields: [
...>     %Anvil.Schema.Field{name: "category", type: :select, required: true, options: ["a", "b"]}
...>   ]
...> )
iex> Anvil.Schema.validate(schema, %{"category" => "a"})
{:ok, %{"category" => "a"}}
iex> Anvil.Schema.validate(schema, %{"category" => "c"})
{:error, [%{field: "category", error: "must be one of: a, b"}]}