I’m trying to set up event handlers that can call Lambda functions when my data gets modified in Amplify Gen 2. While I managed to configure some Lambda functions for user authentication flows, I can’t figure out how to connect them to database operations.
Here’s my data model:
product: a
.model({
id: a.id().required(),
title: a.string().required(),
categoryId: a.id().required(),
category: a.belongsTo("category", "categoryId"),
})
.authorization((allow) => [allow.publicApiKey()]),
In my service layer I’m doing updates like this:
async modifyProduct(product: ProductModifyType): Promise<ProductModifyType> {
try {
return await client.models.product.update(product);
} catch (err) {
console.error("Failed to modify product", product.id);
throw err;
}
}
I need to run calculations on the category totals every time a product gets updated. What’s the best way to hook into these update events and trigger my Lambda function automatically?
have u looked into event sourcing patterns with amplify? how complicated are your category calcs - just basic counts or something more advanced? u might also try onCreate and onUpdate handlers directly in the schema instead of using external triggers.
Use DynamoDB triggers in your Amplify backend - it’s the easiest way. Just create a function in your amplify/backend.ts file that runs automatically when your database changes. Set up a trigger on your product table to call your calculation function whenever records get modified. You’ll need to create a Lambda function for the category calculations, then bind it to the DynamoDB table events with addDynamoDbEventSource. The trigger gets the change event with old and new values, so you know exactly which calculations to update. Works great for category totals since it handles changes in real-time without you having to touch your service layer.
dynamodb streams r the way to go! amplify gen 2 uses dynamodb, so enabling streams on ur table will let u trigger lambda on data updates. just link it to your calcs function and u’ll get auto totals every time. super easy!