Created
December 3, 2022 05:53
-
-
Save leegilmorecode/94bed42e93251979ed6b9e585a335b64 to your computer and use it in GitHub Desktop.
Secondary adapter for publishing events to Amazon EventBridge
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as AWS from 'aws-sdk'; | |
import { PutEventsRequestEntry } from 'aws-sdk/clients/eventbridge'; | |
import { config } from '@config/config'; | |
import { logger } from '@packages/logger'; | |
class NoEventBodyError extends Error { | |
constructor(message: string) { | |
super(message); | |
this.name = 'NoEventBodyError'; | |
} | |
} | |
const eventBridge = new AWS.EventBridge(); | |
// this is a secondary adapter which will publish the event to eventbridge | |
// domain --> use case --> (adapter) | |
export async function publishEvent( | |
event: Record<string, any>, | |
detailType: string, | |
source: string, | |
eventVersion: string, | |
eventDateTime: string | |
): Promise<void> { | |
const eventBus = config.get('eventBus'); | |
if (Object.keys(event).length === 0) { | |
throw new NoEventBodyError('There is no body on the event'); | |
} | |
const createEvent: PutEventsRequestEntry = { | |
Detail: JSON.stringify({ | |
metadata: { | |
eventDateTime: eventDateTime, | |
eventVersion: eventVersion, | |
}, | |
data: { | |
...event, | |
}, | |
}), | |
DetailType: detailType, | |
EventBusName: eventBus, | |
Source: source, | |
}; | |
const subscriptionEvent: AWS.EventBridge.PutEventsRequest = { | |
Entries: [createEvent], | |
}; | |
await eventBridge.putEvents(subscriptionEvent).promise(); | |
logger.info( | |
`event ${detailType} published for ${event.id} to bus ${eventBus} with source ${source}` | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment