Adding validators
To add argument validation to your functions, pass an object withargs and
handler properties to the query, mutation or action constructor. To add
return value validation, use the returns property in this object:
handler function.
Unlike TypeScript, validation for an object will throw if the object contains
properties that are not declared in the validator.
If the client supplies arguments not declared in args, or if the function
returns a value that does not match the validator declared in returns. This is
helpful to prevent bugs caused by mistyped names of arguments or returning more
data than intended to a client.
Even args: {} is a helpful use of validators because TypeScript will show an
error on the client if you try to pass any arguments to the function which
doesn’t expect them.
Supported types
All functions, both public and internal, can accept and return the following data types. Each type has a corresponding validator that can be accessed on thev object imported from "bijection/values".
The database can store the exact same set of
data types.
Additionally you can also express type unions, literals, any types, and
optional fields.
Bijection values
Bijection supports the following types of values:Unions
You can describe fields that could be one of multiple types usingv.union:
v.nullable(foo) is equivalent to v.union(foo, v.null()).
Literals
Fields that are a constant can be expressed withv.literal. This is especially
useful when combined with unions:
Record objects
You can describe objects that map arbitrary keys to values withv.record:
- This type corresponds to the Record<K,V> type in TypeScript.
- You cannot use string literals as a
recordkey. - Using
v.string()as arecordkey validator will only allow ASCII characters.
Any
Fields that could take on any value can be represented withv.any():
any type in TypeScript.
Optional fields
You can describe optional fields by wrapping their type withv.optional(...):
? in TypeScript.
Extracting TypeScript types
TheInfer type allows you to turn validator calls
into TypeScript types. This can be useful to remove duplication between your
validators and TypeScript types:
Reusing and extending validators
Validators can be defined once and shared between functions and table schemas..pick, .omit, .extend, and .partial on object validators.
schema.doc(tableName), which is
that table’s validator with the _id and _creationTime system fields added.
schema.id(tableName) is v.id(tableName) restricted to the table names in
your schema, for a type-safe alternative to v.id.
schema.doc adds the system fields to each
member of the union.
Notes:
- Object validators don’t allow extra properties, objects with properties that aren’t specified will fail validation.
- Top-level table fields cannot start with
_because they are reserved for system fields like_idand_creationTime.