Listen to storage events
Function triggers can be configured to enable event-based workflows when files are uploaded or deleted. To add a function trigger, modify the defineStorage
configuration.
First, in your storage definition, add the following:
amplify/storage/resource.ts
export const storage = defineStorage({ name: 'myProjectFiles', triggers: { onUpload: defineFunction({ entry: './on-upload-handler.ts' }), onDelete: defineFunction({ entry: './on-delete-handler.ts' }) }});
Then create the function definitions at amplify/storage/on-upload-handler.ts
and amplify/storage/on-delete-handler.ts
.
amplify/storage/on-upload-handler.ts
import type { S3Handler } from 'aws-lambda';
export const handler: S3Handler = async (event) => { const objectKeys = event.Records.map((record) => record.s3.object.key); console.log(`Upload handler invoked for objects [${objectKeys.join(', ')}]`);};
amplify/storage/on-delete-handler.ts
import type { S3Handler } from 'aws-lambda';
export const handler: S3Handler = async (event) => { const objectKeys = event.Records.map((record) => record.s3.object.key); console.log(`Delete handler invoked for objects [${objectKeys.join(', ')}]`);};
Now, when you deploy your backend, these functions will be invoked whenever an object is uploaded or deleted from the bucket.