@diy0r/nestjs-rabbitmq
Version:
Nestjs rabbitMQ module
210 lines • 8.5 kB
JavaScript
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.RmqNestjsConnectService = void 0;
const common_1 = require("@nestjs/common");
const constants_1 = require("./constants");
const amqplib_1 = require("amqplib");
const interfaces_1 = require("./interfaces");
const common_2 = require("./common");
let RmqNestjsConnectService = class RmqNestjsConnectService {
constructor(RMQOptions) {
this.RMQOptions = RMQOptions;
this.connection = null;
this.baseChannel = null;
this.replyToChannel = null;
this.isConnected = false;
this.isInitialized = false;
this.logger = RMQOptions.extendedOptions?.appOptions?.logger
? RMQOptions.extendedOptions.appOptions.logger
: new common_2.RQMColorLogger(RMQOptions.extendedOptions?.appOptions?.logMessages);
}
async onModuleInit() {
if (this.isInitialized)
throw Error(constants_1.ROOT_MODULE_DECLARED);
await this.setUpConnect(this.RMQOptions.connectOptions);
await this.setUpChannels();
this.isInitialized = true;
}
async assertExchange(options) {
try {
await this.initializationCheck();
const exchange = await this.baseChannel.assertExchange(options.exchange, options.type, options.options);
return exchange;
}
catch (error) {
throw new Error(`Failed to assert exchange '${options.exchange}': ${error.message}`);
}
}
ack(...params) {
return this.baseChannel.ack(...params);
}
nack(...params) {
return this.baseChannel.nack(...params);
}
async assertQueue(typeQueue, options) {
await this.initializationCheck();
try {
if (typeQueue == interfaces_1.TypeQueue.QUEUE) {
return this.baseChannel.assertQueue(options.queue, options.options);
}
return await this.replyToChannel.assertQueue(options.queue, options.options);
}
catch (error) {
throw new Error(`Failed to assert ${typeQueue} queue: ${error}`);
}
}
async getBaseChannel() {
await this.initializationCheck();
return this.baseChannel;
}
async bindQueue(bindQueue) {
await this.initializationCheck();
try {
await this.baseChannel.bindQueue(bindQueue.queue, bindQueue.source, bindQueue.pattern, bindQueue.args);
}
catch (error) {
throw new Error(`Failed to Bind Queue ,source:${bindQueue.source} queue: ${bindQueue.queue}`);
}
}
async sendToReplyQueue(sendToQueueOptions) {
try {
await this.initializationCheck();
this.replyToChannel.sendToQueue(sendToQueueOptions.replyTo, sendToQueueOptions.content, {
correlationId: sendToQueueOptions.correlationId,
headers: sendToQueueOptions.headers,
});
}
catch (error) {
throw new Error(`Failed to send Reply Queue`);
}
}
async listenReplyQueue(queue, listenQueue, consumeOptions) {
try {
await this.replyToChannel.consume(queue, listenQueue, consumeOptions || {
noAck: true,
});
}
catch (error) {
throw new Error(`Failed to send listen Reply Queue`);
}
}
async listenQueue(queue, listenQueue, consumeOptions) {
try {
await this.baseChannel.consume(queue, listenQueue, consumeOptions || {
noAck: false,
});
}
catch (error) {
throw new Error(`Failed to listen Queue`);
}
}
async publish(sendMessage, confirmationFunction) {
try {
await this.initializationCheck();
this.baseChannel.publish(sendMessage.exchange, sendMessage.routingKey, sendMessage.content, {
replyTo: sendMessage.options.replyTo,
correlationId: sendMessage.options.correlationId,
}, confirmationFunction);
}
catch (error) {
throw new Error(`Failed to send message ${error}`);
}
}
async setUpConnect(connectOptions) {
try {
this.connection = await (0, amqplib_1.connect)(connectOptions, this.RMQOptions.extendedOptions?.socketOptions);
this.isConnected = true;
this.logger.log(constants_1.SUCCESSFUL_CONNECT);
this.connection.on(constants_1.CLOSE_EVENT, err => {
this.isConnected = false;
this.logger.error(`${constants_1.CLOSE_MESSAGE}: ${err.message}`);
this.reconnect(connectOptions);
});
this.connection.on(constants_1.CONNECT_ERROR, err => {
this.logger.error(`${constants_1.CONNECT_FAILED_MESSAGE}: ${err.message}`);
});
this.connection.on(constants_1.CONNECT_BLOCKED, err => {
this.logger.error(`${constants_1.CONNECT_BLOCKED_MESSAGE}: ${err.message}`);
});
}
catch (err) {
this.logger.error(`Failed to connect: ${err.message}`);
}
}
async reconnect(options) {
this.logger.log('Attempting to reconnect...');
setTimeout(async () => {
try {
await this.setUpConnect(options);
}
catch (err) {
this.logger.error(`Reconnection failed: ${err.message}`);
this.reconnect(options);
}
}, constants_1.RECONNECTION_INTERVAL);
}
async setUpChannels() {
try {
const { extendedOptions } = this.RMQOptions;
const isConfirmChannel = extendedOptions?.typeChannel === interfaces_1.TypeChannel.CONFIRM_CHANNEL;
this.baseChannel = isConfirmChannel
? await this.createConfirmChannel()
: await this.createChannel();
this.replyToChannel = await this.createChannel();
if (extendedOptions?.prefetch)
await this.prefetch(extendedOptions.prefetch);
}
catch (error) {
console.error('Error setting up channels:', error);
throw error;
}
}
prefetch(prefetch) {
return this.baseChannel.prefetch(prefetch.count, prefetch.isGlobal);
}
async sendToQueue(queue, content, options) {
try {
await this.initializationCheck();
return this.baseChannel.sendToQueue(queue, content, options);
}
catch (error) {
throw new Error(`Failed to send message ${error}`);
}
}
async initializationCheck() {
if (this.isInitialized)
return;
await new Promise(resolve => setTimeout(resolve, constants_1.INITIALIZATION_STEP_DELAY));
await this.initializationCheck();
}
async createChannel() {
return await this.connection.createChannel();
}
async createConfirmChannel() {
return await this.connection.createConfirmChannel();
}
async onModuleDestroy() {
await this.baseChannel.close();
await this.replyToChannel.close();
await this.connection.close();
}
};
exports.RmqNestjsConnectService = RmqNestjsConnectService;
exports.RmqNestjsConnectService = RmqNestjsConnectService = __decorate([
(0, common_1.Injectable)(),
__param(0, (0, common_1.Inject)(constants_1.RMQ_OPTIONS)),
__metadata("design:paramtypes", [Object])
], RmqNestjsConnectService);
//# sourceMappingURL=rmq-connect.service.js.map