medusa-event-bus-aws
Version:
A Medusa module for seamless integration with AWS EventBridge, enabling real-time event handling in headless e-commerce applications.
61 lines (60 loc) • 2.21 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
const utils_1 = require("@medusajs/framework/utils");
const client_eventbridge_1 = require("@aws-sdk/client-eventbridge");
const os_1 = require("os");
class AwsEventBridgeEventBus extends utils_1.AbstractEventBusModuleService {
client;
logger;
options;
events;
constructor(container, options, declaration) {
super(container, options, declaration);
this.client = container.eventBridgeClient;
this.logger = container.logger;
this.options = options;
this.events = new Map();
}
async emit(eventsData) {
const normalized = Array.isArray(eventsData) ? eventsData : [eventsData];
for (const eventData of normalized) {
await this.groupOrEmitEvent(eventData);
}
}
async releaseGroupedEvents(groupId) {
const grouped = this.events.get(groupId) || [];
for (const event of grouped) {
await this.emitToEventBridge(event);
}
await this.clearGroupedEvents(groupId);
}
async clearGroupedEvents(groupId) {
await Promise.resolve(this.events.delete(groupId));
}
async groupOrEmitEvent(eventData) {
const eventGroupId = eventData.metadata?.eventGroupId;
if (eventGroupId) {
this.groupEvent(eventGroupId, eventData);
}
else {
await this.emitToEventBridge(eventData);
}
}
async emitToEventBridge(eventData) {
const payload = {
EventBusName: this.options.eventBusName,
Source: this.options.eventBusName,
DetailType: eventData.name,
Detail: JSON.stringify(eventData),
};
const command = new client_eventbridge_1.PutEventsCommand({ Entries: [payload] });
await this.client.send(command)
.catch(error => { this.logger.error(`Error sending event to AWS EventBridge:${os_1.EOL} ${error}`); });
}
groupEvent(groupId, eventData) {
const grouped = this.events.get(groupId) || [];
grouped.push(eventData);
this.events.set(groupId, grouped);
}
}
exports.default = AwsEventBridgeEventBus;
;