smart-saga-pattern
Version:
A library implementing the Saga pattern for microservice architecture
92 lines (91 loc) • 2.95 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.RabbitMQAdapter = void 0;
/**
* Adapter for RabbitMQ message broker
* Note: This is a placeholder implementation. In a real implementation,
* you would use a RabbitMQ client library like 'amqplib'.
*/
class RabbitMQAdapter {
/**
* Creates a new RabbitMQAdapter
* @param options RabbitMQ adapter options
*/
constructor(options) {
this.handlers = new Map();
this.connected = false;
this.options = {
exchangeType: 'topic',
...options
};
}
/**
* Connects to RabbitMQ
*/
async connect() {
// In a real implementation, you would connect to RabbitMQ here
console.log(`Connecting to RabbitMQ at ${this.options.url}`);
this.connected = true;
}
/**
* Disconnects from RabbitMQ
*/
async disconnect() {
// In a real implementation, you would disconnect from RabbitMQ here
console.log('Disconnecting from RabbitMQ');
this.connected = false;
}
/**
* Publishes a message to a topic
* @param topic Topic to publish to
* @param message Message to publish
*/
async publish(topic, message) {
this.ensureConnected();
// In a real implementation, you would publish to RabbitMQ here
console.log(`Publishing message to topic '${topic}':`, message);
// Simulate message delivery to subscribers
setTimeout(() => {
const topicHandlers = this.handlers.get(topic);
if (topicHandlers) {
topicHandlers.forEach(handler => {
handler(message).catch(error => {
console.error(`Error handling message on topic '${topic}':`, error);
});
});
}
}, 10);
}
/**
* Subscribes to a topic
* @param topic Topic to subscribe to
* @param handler Handler function for messages
*/
async subscribe(topic, handler) {
this.ensureConnected();
// In a real implementation, you would subscribe to RabbitMQ here
console.log(`Subscribing to topic '${topic}'`);
const handlers = this.handlers.get(topic) || [];
handlers.push(handler);
this.handlers.set(topic, handlers);
}
/**
* Unsubscribes from a topic
* @param topic Topic to unsubscribe from
*/
async unsubscribe(topic) {
this.ensureConnected();
// In a real implementation, you would unsubscribe from RabbitMQ here
console.log(`Unsubscribing from topic '${topic}'`);
this.handlers.delete(topic);
}
/**
* Ensures the adapter is connected
*/
ensureConnected() {
if (!this.connected) {
throw new Error('RabbitMQAdapter is not connected');
}
}
}
exports.RabbitMQAdapter = RabbitMQAdapter;