smart-saga-pattern
Version:
A library implementing the Saga pattern for microservice architecture
72 lines (71 loc) • 1.99 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.SagaParticipant = void 0;
const uuid_1 = require("uuid");
/**
* Represents a participant in a choreography-based Saga
*/
class SagaParticipant {
/**
* Creates a new SagaParticipant
* @param options Options for the participant
* @param publisher Event publisher
* @param subscriber Event subscriber
*/
constructor(options, publisher, subscriber) {
this.handlers = new Map();
this.name = options.name;
this.subscribeTopic = options.subscribeTopic;
this.publishTopic = options.publishTopic;
this.publisher = publisher;
this.subscriber = subscriber;
}
/**
* Starts the participant
*/
async start() {
await this.subscriber.subscribe(this.subscribeTopic, this.handleEvent.bind(this));
}
/**
* Stops the participant
*/
async stop() {
await this.subscriber.unsubscribe(this.subscribeTopic);
}
/**
* Registers a handler for a specific event type
* @param eventType Type of event to handle
* @param handler Handler function
*/
on(eventType, handler) {
this.handlers.set(eventType, handler);
}
/**
* Publishes an event
* @param type Event type
* @param payload Event payload
* @param sagaId ID of the Saga
*/
async publish(type, payload, sagaId) {
const event = {
id: (0, uuid_1.v4)(),
type,
payload,
sagaId,
source: this.name,
timestamp: Date.now()
};
await this.publisher.publish(this.publishTopic, event);
}
/**
* Handles an incoming event
* @param event Event to handle
*/
async handleEvent(event) {
const handler = this.handlers.get(event.type);
if (handler) {
await handler(event);
}
}
}
exports.SagaParticipant = SagaParticipant;