Extending
One of the best parts of @zuze/schema (aside from the cool conditions) is the ability to extend it with your own custom validators/transforms.
Note: There are some special rules about using custom transforms/validators when using the AST API.
#
Creating ValidatorsValidators are simple objects definitions, the only required properties are name
and test
.
For convenience there's a helper method to help in creating custom tests.
No matter what type of validator async or sync the validator must return a boolean or ValidationError, the latter can be created using the createError
method passed in to the validator function.
The signature of a validator test looks like:
To return a ValidationError:
If optionalRef
is not a ref then it will be returned, otherwise the resolved value will be returned:
#
AsyncAsync validators are trivial to create - just use async-await.
Note: async
validators will not be run (a warning will be logged) in the schema is being validated synchronously.
#
Accepting ArgumentsMost validators require arguments to function correct like:
To create a validator that accepts arguments is straightforward:
#
Creating TransformsTransform functions are run in the order they have been added to a SchemaDefinition (unless strict is false). @zuze/schema includes a lot of neat transforms by default, but in case you wanted to extend it, it's pretty easy:
- ast
- functional