-
Notifications
You must be signed in to change notification settings - Fork 2
Description
Z! v1 focused on describing and validating schemas with an emphasis on validation. The public API for v1 was heavily influenced by packages such as Joi, Yup, and Zod from the JavaScript community.
Based on feedback from @yordis, v2 will focus on providing an API that first gives the community an efficient way of describing structs and allows type casting, validation, and other functionality to be layered on.
Minimum Example
defmodule Book do
use Z.Struct
schema do
field :title
field :author
field :description
field :price
field :read_at
end
endThe example above is the most basic form of defining a struct and is equivalent to
defmodule Book do
defstruct [:title, :author, :description, :price, :read_at]
endThe base API will be able to describe structs with all of the built-in functionality provided by vanilla Elixir. This includes defining keys, default values, @enforce_keys, and typespec
Base API Example
defmodule Book do
use Z.Struct
schema do
field :title, enforce: true, typespec: String.t
field :author, default: "Unknown", enforce: true, typespec: String.t
field :description, typespec: String.t
field :price, default: 0.0
field :read_at
end
endThe above example is equivalent to
defmodule Book do
@enforce_keys [:title, :author]
defstruct [:title, :description, :read_at, author: "Unknown", price: 0.0]
@type t :: %Book{
title: String.t(),
author: String.t(),
description: String.t()
}
endIn v1 field accepted a name, type, and rules. One thing that became obvious is that you may want to validate a struct using different rules depending on the use case. For this reason, we want to provide convenient helper functions for defining and composing your own validation functions.
Also, all rules can be categorized as a cast, mutation, or validation. Where cast is a rule that converts from one type to another, mutation is a rule that changes the value but doesn't change the type, and validation is a rule that makes an assertion about the value.
By bucketing each rule into one of these three categories, we can more granularly layer on our validation.