UNPKG

@goparrot/pubsub-event-bus

Version:
72 lines 3.31 kB
import { __decorate, __metadata } from "tslib"; import { Inject, Optional } from '@nestjs/common'; import * as RabbitManager from 'amqp-connection-manager'; import { cloneDeep, set } from 'lodash'; import { LoggerProvider } from '../provider'; import { CQRS_CONNECTION_MANAGER_OPTIONS, CQRS_CONNECTION_NAME, CQRS_CONNECTION_URLS, CQRS_EXCHANGE_CONFIG } from '../utils/configuration'; export class PubsubManager { get connection() { if (!this.connection$) { throw new Error('Amqp connection has not been initialized'); } return this.connection$; } get channelWrapper() { if (!this.channelWrapper$) { throw new Error('Amqp channel has not been initialized'); } return this.channelWrapper$; } async setupChannel(_channel) { } initConnectionIfRequired() { if (this.connection$) { return; } const options = cloneDeep(this.connectionManagerOptions); if (!options.connectionOptions?.clientProperties.connection_name && this.connectionName) { const connectionName = `${this.connectionName}:${this.constructor.name.toLowerCase()}`; set(options, 'connectionOptions.clientProperties.connection_name', connectionName); } this.connection$ = RabbitManager.connect(this.urls, options) .on('connect', () => this.logger().log('Amqp connection established', this.constructor.name)) .on('disconnect', (arg) => this.logger().error(arg.err.message, undefined, this.constructor.name)) .on('connectFailed', (arg) => this.logger().error(arg.err.message, undefined, this.constructor.name)) .on('blocked', (arg) => this.logger().error(`Connection blocked, ${arg.reason}`, undefined, this.constructor.name)) .on('unblocked', () => this.logger().log('Connection unblocked', this.constructor.name)); } initChannelIfRequired() { if (this.channelWrapper$) { return; } this.channelWrapper$ = this.connection .createChannel({ json: true, setup: this.setupChannel.bind(this) }) .on('connect', () => this.logger().log(`Amqp channel created`, this.constructor.name)) .on('error', (err, { name }) => this.logger().error(`Amqp channel error: ${err.message}`, err.stack, name ?? this.constructor.name)) .on('close', () => this.logger().log(`Amqp channel closed`, this.constructor.name)); } async onModuleDestroy() { await this.channelWrapper$?.close(); await this.connection$?.close(); } logger() { return LoggerProvider.logger; } } __decorate([ Inject(CQRS_CONNECTION_NAME), Optional(), __metadata("design:type", String) ], PubsubManager.prototype, "connectionName", void 0); __decorate([ Inject(CQRS_CONNECTION_URLS), __metadata("design:type", Object) ], PubsubManager.prototype, "urls", void 0); __decorate([ Inject(CQRS_EXCHANGE_CONFIG), __metadata("design:type", Object) ], PubsubManager.prototype, "assertExchangeOptions", void 0); __decorate([ Inject(CQRS_CONNECTION_MANAGER_OPTIONS), __metadata("design:type", Object) ], PubsubManager.prototype, "connectionManagerOptions", void 0); //# sourceMappingURL=PubsubManager.js.map