AST
The Abstract Syntax Tree (AST) format for @zuze/schema is intuitive. It mirrors the functional API virtually completely.
#
Passing ArgumentsWhen it comes to tests
and transforms
, each item in the array is evaluated as a function name. Or, in the case of the item in the array being an array itself, the first item is used as the function name and all subsequent values in the array will be passed to it as arguments.
- ast
- functional
#
ConditionsUsing the AST API conditions is an array of ASTCondition objects:
When when
is an array, if ANY of the ObjectAST's
are matched (using matches), the then
will be applied (if present). If not, the otherwise
will be applied (if present).
#
RefsRefs are created in AST via ASTRef
#
Custom Transforms/ValidatorsBy default, all transforms/validators available in @zuze/schema are available via the AST. But part of the beauty of @zuze/schema is being able to create your own transforms/validators.
When using the AST, each custom transform/validator must be a function (called with the options passed to createSchema(s)
/matches
that returns a function called with the arguments in the AST.
The user-supplied transforms/validators need to be given in options argument of createSchema(s)
/matches
.
#
AST TransformsSome transforms in @zuze/schema
have AST-specific implementations:
#
unique#
compactcompact accepts a rejector function in the functional form. In the AST form it accepts an argument that will be passed to matches. Any value in the array that passes matches
will be excluded.
#
AST ValidatorsThere are some functional validators that require some tweaking to be mirrored by the AST - namely oneOfType
, negate
, and serial
.
#
oneOfType#
negate#
serialAs you'll remember, serial is a validator that runs the ValidatorDefinitions passed to it sequentially, stopping after the first one fails. It's only necessary when dependent async validations.
#
API#
matchesmatches(AST | AST[], options?: ASTMatchesOptions): boolean | Promise<boolean>
Not to be confused with the matches validator:
matches
runs synchronously BY DEFAULT unless sync:false
is passed as an option.
It is equivalent to running isValidSync on a SchemaDefinition
matches
accepts AST or an array of ASTs and returns true (or a Promise resolving to true) if any of the ASTs are valid. If you pass {how:'all'}
(see ASTMatchesOptions) as an option then it will only return true if all of the ASTs are valid.
#
createSchemacreateSchema(schema: AST, options?: ASTSchemaOptions): Schema
Converts an AST to a SchemaDefinition that can be passed to one of the functional methods like cast, validate/validateSync, isValid/isValidSync, validateAt/validateAtSync
#
createSchemascreateSchemas(schemas: AST | AST[], options?: ASTSchemaOptions): Schema[]
Same as createSchema except it returns an array of SchemaDefinitions and can accept a single AST or an array