UNPKG

smart-saga-pattern

Version:

A library implementing the Saga pattern for microservice architecture

106 lines (105 loc) 3.46 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.RedisAdapter = void 0; /** * Adapter for Redis Pub/Sub * Note: This is a placeholder implementation. In a real implementation, * you would use a Redis client library like 'ioredis'. */ class RedisAdapter { /** * Creates a new RedisAdapter * @param options Redis adapter options */ constructor(options) { this.handlers = new Map(); this.connected = false; this.options = { prefix: "saga:", ...options, }; } /** * Connects to Redis */ async connect() { // In a real implementation, you would connect to Redis here console.log(`Connecting to Redis at ${this.options.url}`); this.connected = true; } /** * Disconnects from Redis */ async disconnect() { // In a real implementation, you would disconnect from Redis here console.log("Disconnecting from Redis"); this.connected = false; } /** * Publishes a message to a channel * @param topic Channel to publish to * @param message Message to publish */ async publish(topic, message) { this.ensureConnected(); const channel = this.getChannelName(topic); // In a real implementation, you would publish to Redis here console.log(`Publishing message to channel '${channel}':`, message); // Simulate message delivery to subscribers setTimeout(() => { const topicHandlers = this.handlers.get(topic); if (topicHandlers) { console.log(`Delivering message to ${topicHandlers.length} handlers for topic '${topic}'`); topicHandlers.forEach((handler) => { handler(message).catch((error) => { console.error(`Error handling message on channel '${channel}':`, error); }); }); } else { console.log(`No handlers found for topic '${topic}'`); } }, 10); } /** * Subscribes to a channel * @param topic Channel to subscribe to * @param handler Handler function for messages */ async subscribe(topic, handler) { this.ensureConnected(); const channel = this.getChannelName(topic); // In a real implementation, you would subscribe to Redis here console.log(`Subscribing to channel '${channel}'`); const handlers = this.handlers.get(topic) || []; handlers.push(handler); this.handlers.set(topic, handlers); } /** * Unsubscribes from a channel * @param topic Channel to unsubscribe from */ async unsubscribe(topic) { this.ensureConnected(); const channel = this.getChannelName(topic); // In a real implementation, you would unsubscribe from Redis here console.log(`Unsubscribing from channel '${channel}'`); this.handlers.delete(topic); } /** * Gets the full channel name with prefix * @param topic Base topic name */ getChannelName(topic) { return `${this.options.prefix}${topic}`; } /** * Ensures the adapter is connected */ ensureConnected() { if (!this.connected) { throw new Error("RedisAdapter is not connected"); } } } exports.RedisAdapter = RedisAdapter;