UNPKG

llamajs

Version:

A dynamic logger for the dynamic developer

63 lines 2.25 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const transport_1 = require("../transport"); const amqp = require("amqplib"); class RabbitMqTransport extends transport_1.Transport { constructor(config) { super(); this.configure(config); } init() { if (!this.amqpConnection) return this.connect(); return Promise.resolve(this.amqpConnection); } async connect() { const connection = await amqp.connect(`amqp://${this.config.username}:${this.config.password}@${this.config.host}`); connection.on('error', (error) => { if (error.message !== 'Connection closing') { throw new Error(`[RabbitMQ] ${error.message}`); } }); this.amqpConnection = connection; return connection; } async close() { this.amqpConnection.close(); } async startPublisher() { if (!this.amqpConnection) { throw new Error('[RabbitMQ]: connection is not open'); } else { const channel = await this.amqpConnection.createChannel(); channel.assertExchange(this.config.exchange.name, this.config.exchange.type, this.config.exchange.options); channel.on('error', (error) => { throw new Error(`[RabbitMQ] channel error: ${error.message}`); }); this.amqpChannel = channel; } } async publish(message, routingKey) { if (!this.amqpConnection) { await this.connect(); } if (!this.amqpChannel) { await this.startPublisher(); } try { this.amqpChannel.publish(this.config.exchange.name, routingKey || '', Buffer.from(message), { persistent: this.config.persistent }); } catch (error) { throw new Error(`[RabbitMQ]: ${error.message}`); } } pass(message, messageConfig) { this.publish(message, messageConfig.routingKey); } async configure(config) { this.config = config; } } exports.RabbitMqTransport = RabbitMqTransport; //# sourceMappingURL=rabbitMQ.transport.js.map