You may want to read About Data Hooks before following these instructions.
Note: Data hooks run on the server. This means that any logs your code produces do not appear in the Developer Console in Preview mode. Rather, use the built-in Site Events tool to see your logs.
The code for data hooks is stored in a file called data.js in the Backend section of your site.
You can add this code to the file by writing it yourself, or generate template code using the Velo Sidebar.
To generate a template for a hook using the sidebar:
The code that registers a hook follows the following format:
The collectionName
is the name of the collection that the hook will be registered to. The hookName
is the type of hook.
The hook function takes two parameters. The first parameter is dependent on which hook was called. It can be either the current item, the current item's ID, the query, count, or error. The second parameter is an object that contains contextual information about the hook, such as the name of the collection the hook affects, the current user's ID, and the permissions role of the current user.
The hook function is expected to return a specific type. If it returns a value of a different type, that value is ignored.
For full details on parameters and expected return values for the different types of hooks, see the Data API reference.
A hook on an interaction that affects multiple items in the collection will be called repeatedly, once for each of the items.
Notes:
data.js
. For more information, see Module Export Syntax.In general terms, hooks work in the following manner:
For example, in the following hook:
If we look at the item inserted into the collection, we'll see that its title is in all uppercase letters.
You can use hooks to prevent the addition of an item to a collection if it doesn't meet certain requirements. The following example uses the beforeInsert()
hook to validate an email address field. If the email is invalid, the function returns Promise.reject()
and the item is not added to the collection.
Hooks that tigger after a function has executed do not affect the item in the collection. They can only affect the item returned by the function, which is a copy of the item in the collection.
Note Do not use the `afterQuery()` hook to modify collection data. This can cause the Content Management System (CMS) to fail when loading. If you need to modify the results of queries before performing other data operations use the appropriate hook, such as `beforeInsert()` or `beforeUpdate()`.
The following API is used in the code in this article. To learn more, see the API Reference.