Zoi - schema validation library inspired by Zod

v0.8.2 released :rocket:

Hey everyone, this release brings schema documentation introspection for Zoi.object/2 and Zoi.keyword/2 types.

Example

One common example is when passing maps or keyword lists as parameters in your function, it’s often hard to keep track of what keys are expected and their types.


@spec create_user(map(), keyword()) :: {:ok, User.t()} | {:error, Ecto.Changeset.t()}
def create_user(params, opts \\ []) do
    ## creating user
end

and overtime you may lose track of what params or opts are being passed. Zoi can help you to give more meaning to these arguments:

@create_user_params Zoi.object(%{
  name: Zoi.string(description: "The user first name"),
  age: Zoi.integer(description: "The user age") |> Zoi.min(0) |> Zoi.optional(),
  email: Zoi.email(description: "The user email")
})

@create_user_opts Zoi.keyword([
  skip_checks: Zoi.boolean(description: "Wether to skip validation checks")
])

@doc """
Creates a new user.

Params:
#{Zoi.describe(@create_user_params)}

Options:
#{Zoi.describe(@create_user_opts)}
"""
@spec create_user(
      unquote(Zoi.type_spec(@create_user_params)),
      unquote(Zoi.type_spec(@create_user_opts))
    ) :: {:ok, User.t()} | {:error, Ecto.Changeset.t()}
def create_user(params, opts \\ []) do
    # parsing params and opts to ensure they conform to the schema
    params = Zoi.parse!(@create_user_params, params)
    opts = Zoi.parse!(@create_user_opts, opts)
    ## creating user
end

For library authors, this is a great way to document the expected input schemas for functions, the example above would generate the following documentation:

Creates a new user.

Params:
* `:name` (`t:String.t/0`) - Required. The user first name
* `:age` (`t:integer/0`) - The user
* `:email` (`t:String.t/0`) - Required. The user email

Opts:
* `:skip_checks` (`t:boolean/0`) - Wether to skip validation checks

The doc output was inspired by nimble_options, which offers a format compatible with HexDocs, and users will be able to check each argument and their types directly on the function documentation published in hexdocs.

More details in the oficial docs.

Release v0.8.2: zoi | Hex

3 Likes