UNPKG

@bgaldino/nestjs-rabbitmq

Version:

A different way of configuring your RabbitMQ

116 lines 6.17 kB
"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 __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; var RabbitMQService_1; Object.defineProperty(exports, "__esModule", { value: true }); exports.RabbitMQService = void 0; const common_1 = require("@nestjs/common"); const node_crypto_1 = require("node:crypto"); const amqp_connection_manager_1 = require("./amqp-connection-manager"); const rabbitmq_consumers_1 = require("./rabbitmq-consumers"); const faster_stable_stringify_1 = __importDefault(require("faster-stable-stringify")); const helper_1 = require("./helper"); let RabbitMQService = RabbitMQService_1 = class RabbitMQService { constructor() { var _a, _b, _c; this.logger = (_c = (_b = (_a = amqp_connection_manager_1.AMQPConnectionManager.rabbitModuleOptions) === null || _a === void 0 ? void 0 : _a.extraOptions) === null || _b === void 0 ? void 0 : _b.loggerInstance) !== null && _c !== void 0 ? _c : new common_1.Logger(RabbitMQService_1.name); } onApplicationBootstrap() { var _a; this.logType = (_a = process.env.RABBITMQ_LOG_TYPE) !== null && _a !== void 0 ? _a : amqp_connection_manager_1.AMQPConnectionManager.rabbitModuleOptions.extraOptions.logType; } /** * Check status of the main conenection to the broker. * @returns {number} 1 - Online | 0 - Offline */ checkHealth() { return amqp_connection_manager_1.AMQPConnectionManager.consumerConn.isConnected() && amqp_connection_manager_1.AMQPConnectionManager.publisherConn.isConnected() ? 1 : 0; } /** * Publishes a message to the broker. Every published message needs its exchange and routingKey to be properly routed * @param {string} exchangeName - Name of the exchange * @param {string} routingKey - Publish routing key * @param {T} the message that will be published to RabbitMQ. All messages will be transformed to JSON. * @param {PublishOptions} options - Any custom options that you want to send with the message such as headers or properties * @returns {Promise<boolean>} Returns a promise of confirmation. * If **TRUE** it means that the message arrived and was successfully delivered to an exchange or queue. * If **FALSE** or an error is thrown, the message was not published ! */ async publish(exchangeName, routingKey, message, options) { let hasErrors = null; const start = process.hrtime.bigint(); const defaultHeaders = { correlationId: (0, node_crypto_1.randomUUID)(), headers: { "x-application-headers": { "original-exchange": exchangeName, "original-routing-key": routingKey, "published-at": new Date().toISOString(), }, }, persistent: true, deliveryMode: 2, }; try { await amqp_connection_manager_1.AMQPConnectionManager.publishChannelWrapper.publish(exchangeName, routingKey, (0, faster_stable_stringify_1.default)(message), (0, helper_1.merge)(defaultHeaders, options)); } catch (e) { hasErrors = e; } finally { this.inspectPublisher(exchangeName, routingKey, message, process.hrtime.bigint() - start, options, hasErrors); } return !hasErrors; } async createConsumers() { var _a; if (amqp_connection_manager_1.AMQPConnectionManager.isConsumersLoaded) throw new Error("Consumers already initialized. If you wish to start it manually, see consumeManualLoad"); const consumerOptionList = (_a = amqp_connection_manager_1.AMQPConnectionManager.rabbitModuleOptions.consumerChannels) !== null && _a !== void 0 ? _a : []; const consumerList = []; for (const consumerEntry of consumerOptionList) { const consumerOptions = consumerEntry.options; const consumer = await new rabbitmq_consumers_1.RabbitMQConsumer(amqp_connection_manager_1.AMQPConnectionManager.consumerConn, amqp_connection_manager_1.AMQPConnectionManager.rabbitModuleOptions, amqp_connection_manager_1.AMQPConnectionManager.publishChannelWrapper).createConsumer(consumerOptions, consumerEntry.messageHandler); consumerList.push(consumer); } this.logger.debug("Initiating RabbitMQ consumers manually"); amqp_connection_manager_1.AMQPConnectionManager.isConsumersLoaded = true; return consumerList; } inspectPublisher(exchange, routingKey, content, elapsedTime, properties, error) { if (!["publisher", "all"].includes(this.logType) && !error) return; const logLevel = error ? "error" : "log"; const logData = { logLevel, type: "publisher", duration: elapsedTime.toString(), correlationId: properties === null || properties === void 0 ? void 0 : properties.correlationId, title: `[AMQP] [PUBLISH] [${exchange}] [${routingKey}]`, binding: { exchange, routingKey }, publishedMessage: { content, properties, }, }; if (error) logData["error"] = error; this.logger[logLevel](logData); } }; exports.RabbitMQService = RabbitMQService; exports.RabbitMQService = RabbitMQService = RabbitMQService_1 = __decorate([ (0, common_1.Injectable)() ], RabbitMQService); //# sourceMappingURL=rabbitmq-service.js.map