Triggers
Execute a function in response to a change in the database.
To create an executable, decorate a function with the @trigger
decorator within a class that extends the base SquidService
class.
The following example shows a trigger that is executed on a user change to the users
database collection:
import { SquidService, trigger, TriggerRequest } from '@squidcloud/backend';
export class ExampleService extends SquidService {
@trigger('userChange', 'users')
async handleUserChange(request: TriggerRequest): Promise<void> {
// TODO - add your business logic here
}
}
If the function is triggered by a database other than the built-in database, then the integration ID must be specified as the third parameter in the @trigger decorator. For example:
@trigger('userChange', 'User', 'HrDatabase')
The trigger takes the following parameters:
Name | Type | Description |
---|---|---|
id | string | The id of the trigger. Should be unique. |
collectionName | string | The name of the collection to trigger on. |
integrationId? | string | The id of the integration to trigger on. If not provided, the built_in_db integration is used. |
The trigger request provides the following information on the change:
{
squidDocId: SquidDocId; // the primary key for the document
mutationType: MutationType; // the type of operation performed
docBefore?: T; // the document's previous state
docAfter?: T; // the document's updated state
}
To allow Squid to discover the trigger and the rest of the functions in the same service, make sure the service is exported in the service/index.ts
file:
export * from './example-service';
For more information, view the (API documentation)[/docs/api-reference/backend-sdk-reference/exports#trigger] for the trigger decorator.