Zoi.Schema (Zoi v0.10.7)

View Source

Utilities for traversing and transforming Zoi schemas.

This module provides functions to recursively walk through schema structures and apply transformations. This is useful for applying defaults, enabling features like coercion, or wrapping types across an entire schema tree.

The traversal is post-order, meaning child nodes are transformed before their parents, allowing transformations to work with already-processed nested schemas.

Examples

# Enable coercion on all types
schema = Zoi.object(%{
  name: Zoi.string(),
  age: Zoi.integer()
})
|> Zoi.Schema.traverse(&Zoi.coerce/1)

# Apply nullish to all fields
schema
|> Zoi.Schema.traverse(&Zoi.nullish/1)

# Conditional transformation based on field path
schema = Zoi.object(%{
  password: Zoi.string(),
  email: Zoi.string()
})
|> Zoi.Schema.traverse(fn node, path ->
  if :password in path do
    node
  else
    Zoi.coerce(node)
  end
end)

# Chain multiple transformations
schema
|> Zoi.Schema.traverse(&Zoi.nullish/1)
|> Zoi.Schema.traverse(&Zoi.coerce/1)

Summary

Functions

Traverses a schema tree and applies a transformation function to each node.

Functions

traverse(schema, fun)

@spec traverse(Zoi.schema(), function()) :: Zoi.schema()

Traverses a schema tree and applies a transformation function to each node.

The traversal walks through nested schemas (objects, arrays, unions, maps, tuples, etc.) and applies the transformation function to each child node. The root node is not transformed.

The transformation function receives the current node and optionally the path (list of field keys showing the location in the schema tree, e.g., [:user, :address, :street]).

Examples

# Enable coercion on all nested fields
schema
|> Zoi.Schema.traverse(&Zoi.coerce/1)

# Apply transformation conditionally using path
schema
|> Zoi.Schema.traverse(fn node, path ->
  if :password in path do
    node
  else
    Zoi.coerce(node)
  end
end)