Field-level hooks offer incredible potential for encapsulating your logic. They help to isolate concerns and package up functionalities to be easily reusable across your projects.
Example use cases include:
owner
relationship to a Document based on the req.user.id
beforeValidate
and afterRead
hooksbeforeValidate
hookslug
with beforeValidate
beforeChange
hookAll field types provide the following hooks:
beforeValidate
beforeChange
afterChange
afterRead
Example field configuration:
All field-level hooks are formatted to accept the same arguments, although some arguments may be undefined
based on which field hook you are utilizing.
Field Hooks receive one args
argument that contains the following properties:
Option | Description |
---|---|
data | The data passed to update the document within create and update operations, and the full document itself in the afterRead hook. |
siblingData | The sibling data passed to a field that the hook is running against. |
findMany | Boolean to denote if this hook is running against finding one, or finding many within the afterRead hook. |
operation | A string relating to which operation the field type is currently executing within. Useful within beforeValidate , beforeChange , and afterChange hooks to differentiate between create and update operations. |
originalDoc | The full original document in update operations. In the afterChange hook, this is the resulting document of the operation. |
previousDoc | The document before changes were applied, only in afterChange hooks. |
previousSiblingDoc | The sibling data from the previous document in afterChange hook. |
req | The Express request object. It is mocked for Local API operations. |
value | The value of the field. |
previousValue | The previous value of the field, before changes were applied, only in afterChange hooks. |
All field hooks can optionally modify the return value of the field before the operation continues. Field Hooks may optionally return the value that should be used within the field.
Payload exports a type for field hooks which can be accessed and used as follows: