Collection hook

This is the official documentation of the forestadmin-agent-django and forestadmin-agent-flask Python agents.

Forest Admin allows customizing at a very low level the behavior of any given Collection via the usage of Collection Hooks.

Collection Hooks are a very powerful feature and require special care when using them.

How it works

Any given Collection should implement all of the following functions:

  • list

  • create

  • update

  • delete

  • aggregate

The Collection Hooks feature allows executing code before and/or after any of these functions, providing an easy way to interact with your Collections.

To declare a Hook on a Collection, the following information is required:

  • A lifecycle position (Before | After)

  • An action type (List | Create | Update | Delete | Aggregate)

  • A callback, that will receive a context matching the provided hook position and hook definition.

A single Collection can have multiple Hooks with the same position and the same type. They will run in their declaration order. Collection Hooks are only called when the Collection function is contacted by the UI. This means that any usage of the Forest Admin query interface will not trigger them.

Basic use cases

In the following example, we want to prevent a set of users from updating any records of the Transactions table. We want to check if the user email is allowed to update a record via an external API call.

from forestadmin.datasource_toolkit.decorators.hook.context.update import (
    HookBeforeUpdateContext
)

async def transaction_before_update_fn(context: HookBeforeUpdateContext):
    is_allowed = my_function_to_check_user_is_allowed(context.caller.email)
    if not is_allowed:
        context.throw_forbidden_error(f"{context.caller.email} is not allowed")

agent.customize_collection("Transactions").add_hook(
    "Before", "Update", transaction_before_update_fn
)

Another good example would be the following: Each time a new User is created in the database, I want to send him an email.

agent.customize_collection("User").add_hook(
    "After",
    "Create",
    lambda context: MyEmailSender.send_email(
        {
            "from": "erlich@bachman.com",
            "to": context.records[0]['email'],
            "message": "Hey, a new account was created with this email.",
        }
    ),
)

Last updated