UNPKG

@eventstore.net/event.store

Version:

A simple and fast EventStore that support multiple persistence and notification providers

48 lines 1.76 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const amqp = require("amqplib"); /** * A Publisher that use RabbitMQ to message communications. */ class RabbitMQPublisher { constructor(url) { this.exchanges = new Set(); this.url = url; } async publish(message) { const channel = await this.getChannel(); await this.ensureExchange(message.stream.aggregation, channel); return await channel.publish(message.stream.aggregation, '', Buffer.from(JSON.stringify(message))); } async subscribe(aggregation, subscriber) { const channel = await this.getChannel(); await this.ensureExchange(aggregation, channel); const q = await channel.assertQueue('', { exclusive: true }); channel.bindQueue(q.queue, aggregation, ''); const response = await channel.consume(q.queue, (msg) => { subscriber(JSON.parse(msg.content.toString())); }, { noAck: true }); const consumerTag = response.consumerTag; return { remove: async () => { await channel.cancel(consumerTag); await channel.deleteQueue(q.queue); } }; } async ensureExchange(aggregation, channel) { if (!this.exchanges.has(aggregation)) { await channel.assertExchange(aggregation, 'fanout', { durable: false }); this.exchanges.add(aggregation); } } async getChannel() { if (!this.channel) { const conn = await amqp.connect(this.url); this.channel = await conn.createChannel(); } return this.channel; } } exports.RabbitMQPublisher = RabbitMQPublisher; //# sourceMappingURL=rabbitmq.js.map