JSONSchex.Schema (jsonschex v0.7.0)

Copy Markdown View Source

Compile-time helpers for embedding compiled JSON Schemas directly into modules.

Use compile!/2 when the schema is fully known at compile time, such as in generated modules, router metadata, module attributes, Plug/Phoenix code, and test fixtures.

Examples

iex> require JSONSchex.Schema
iex> schema = JSONSchex.Schema.compile!(%{"type" => "integer", "minimum" => 10})
iex> JSONSchex.validate(schema, 10)
:ok

iex> defmodule JSONSchexSchemaMacroExample do
...>   require JSONSchex.Schema
...>   @schema JSONSchex.Schema.compile!(%{"type" => "string", "format" => "email"}, format_assertion: true)
...>   def schema, do: @schema
...> end
iex> {:error, [_]} = JSONSchex.validate(JSONSchexSchemaMacroExample.schema(), "not-an-email")

Summary

Functions

Compiles a static schema literal at compile time and embeds the compiled JSONSchex.Types.Schema directly into the caller module.

Compiles a static JSON Schema fragment at compile time and embeds the compiled JSONSchex.Types.Schema directly into the caller module.

Functions

compile!(schema_ast, opts_ast \\ [])

(macro)

Compiles a static schema literal at compile time and embeds the compiled JSONSchex.Types.Schema directly into the caller module.

The schema argument must be a compile-time literal map or boolean. Options must also be compile-time literals. If you pass :loader, prefer a remote capture such as &MyLoader.fetch/1 so the compiled schema remains embeddable.

Options

The available options are the same as JSONSchex.compile/2:

  • :loader(uri -> {:ok, map()} | {:error, term()}) for remote $ref schemas

  • :base_uri — Starting base URI for resolving relative references
  • :format_assertion — Enable strict format validation (default: false)
  • :content_assertion — Enable strict content vocabulary validation (default: false)

Examples

iex> require JSONSchex.Schema
iex> schema = JSONSchex.Schema.compile!(%{"type" => "string", "format" => "email"}, format_assertion: true)
iex> {:error, [_]} = JSONSchex.validate(schema, "not-an-email")

compile_fragment!(document_ast, opts_ast)

(macro)

Compiles a static JSON Schema fragment at compile time and embeds the compiled JSONSchex.Types.Schema directly into the caller module.

Accepts a containing document plus options. Local references inside the fragment resolve against the containing document, which is useful for OpenAPI 3.1 request/response schemas.

Examples

iex> require JSONSchex.Schema
iex> schema = JSONSchex.Schema.compile_fragment!(
...>   %{"components" => %{"schemas" => %{"Name" => %{"type" => "string"}}}, "schema" => %{"$ref" => "#/components/schemas/Name"}},
...>   entry_pointer: "#/schema"
...> )
iex> JSONSchex.validate(schema, "Alice")
:ok