How do I subscribe to an event?
Objective: This article explains how to subscribe to an event and configure an AWS lambda function to execute when the event is fired.
Steps:
This article is based on the new event that is demonstrated in How do I add a new event?
- Add a new AWS serverless function resource and log group in the desired service's event templates file.
services/<service>/events/template.yaml
- Add the service event handler.
services/<service>/events/handlers/<function name>/index.ts
- This is almost always the
- Add the module event handler logic.
modules/<module>/events/handlers/...
- Register the event handler to the module's event handler builder.
modules/<module>/events/handlers.ts
- Build and test.
Example:
Step 1
# AWS function and log group configuration
# services/<service>/events/template.yaml
Resources:
...
# Lambda function
MyModelCreatedFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: dist/my-model-created # <-- Must match the file name of the service handler in step 2.
Handler: index.handler
FunctionName: my-module-my-model-created
Timeout: 120
Policies:
- Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- logs:CreateLogStream
- logs:DescribeLogStreams
- logs:PutLogEvents
Resource: !GetAtt MyModelCreatedLogGroup.Arn
- Effect: Allow
Action:
- cognito-idp:AdminUpdateUserAttributes
Resource: !Sub 'arn:aws:cognito-idp:${AWS::Region}:${AWS::AccountId}:*'
Events:
Trigger:
Type: EventBridgeRule
Properties:
EventBusName: !ImportValue platform-infrastructure-services-event-bus-name
Pattern:
source:
- platform
detail-type:
- MyModelCreated # <-- The name of the event
# Log group
MyModelCreatedLogGroup:
Type: AWS::Logs::LogGroup
Properties:
LogGroupName: !Sub /aws/lambda/customers-my-model-created
RetentionInDays:
'Fn::If':
- IsProduction
- 30
- 5
Step 2
// Service event handler
// services/<service>/events/handlers/<function name>/index.ts
import { manifest } from '@hectare/platform.modules.customers.events'
import * as Sentry from '@sentry/node'
import { LambdaHandler } from '@hectare/platform.components.context'
const lambdaHandler = new LambdaHandler(manifest)
Sentry.init(lambdaHandler.sentry())
export const handler = async (event: unknown, context: unknown) => {
await lambdaHandler.handle(event, context)
}
Step 3
// Module event handler
// modules/<module>/events/handlers/my-model-created.ts
import { type EventHandler, Context } from '@hectare/platform.components.context'
export const myModelCreated: EventHandler = async (context: Context): Promise<void> => {
// TODO: Implement logic here
console.log('Hello world!')
}
Step 4
// modules/<module>/events/handlers.ts
...
import { myModelCreated as MyModelCreated } from './handlers/my-model-created.js'
const eventHandlers = EventHandlersBuilder.create()
...
.addHandler('MyModelCreated', MyModelCreated)
.done()
export default eventHandlers
Related Articles: