Ensure you update the collection name as needed and the logic to verify if the user can perform the update operation.
src/index.ts
importtype { Agent } from'@forestadmin/forest-cloud';import { Schema } from'../typings';exportdefaultfunctioncustomizeAgent(agent:Agent<Schema>) {agent.customizeCollection('contacts', (collection) => {collection.addHook('Before','Update',async (context) => {constisAllowed=false; // Replace this line by your own logicif (!isAllowed) {context.throwForbiddenError(`${context.caller.email} is not allowed!`); } }); });}
To make the code easier to read, all the code snippets below should be wrapped in the following code.
Adding a collection hook
Collection hooks are triggered exclusively by UI interactions. They are not executed by backend processes or other interactions outside the Forest Admin UI.
To add a hook on a collection, you need to call the addHook() method on the collection instance.
Arguments:
position*String: Indicate when the hook is executed relative to the default logic. Use Before or After.
type* String: The operation type, which can be Aggregate, Create, Delete, List or Update.
handle*Function: An async function that contains your hook logic, which is executed before or after (depending on position) the default operation.
contextObject: The context object includes a caller object. This nested object contains information about the current user, such as the user's timezone and email address, along with other relevant properties.
Note that a single collection can support multiple hooks of the same type and position. These hooks execute sequentially, based on their order of declaration.
Overriding a collection
This feature should be implemented with caution and full understanding. It's important to note that the default behavior will not execute. Therefore, it is your responsibility to anticipate all the potential use cases to ensure the operation's correct usage.
To override the default behavior of an operation, you can call overrideCreate(), overrideUpdate(), or overrideDelete(), as needed.
Create
Arguments:
contextObject: The context object includes a data object. This nested object contains the data intended for creation.
This method must returns an array of created records.
Update
Arguments:
contextObject: The context object includes a filter and a data objects. These nested objects contains respectively the records targeted and the data for the update.
Delete
Arguments:
contextObject: The context object includes a filter object. This nested object contains the records targeted.
Examples
Check permissions before a record update using a Before Update hook
Send an email after a record creation using a After Create hook