UNPKG

@haku-sci/utils

Version:

utils from haku-sci. Library only

142 lines 6.11 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 __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.RabbitMqService = void 0; exports.HakuSubscribe = HakuSubscribe; const nestjs_rabbitmq_1 = require("@golevelup/nestjs-rabbitmq"); const common_1 = require("@nestjs/common"); const rabbitMQutils = require("./constants"); const utils = require("../utils"); const axios_1 = require("axios"); const microservices_1 = require("@nestjs/microservices"); const core_1 = require("@nestjs/core"); const rabbit_mq_module_1 = require("../rabbit-mq/rabbit-mq.module"); const rabbitMqApiAuth = { username: process.env.RABBITMQ_USERNAME, password: process.env.RABBITMQ_PASSWORD, }; let RabbitMqService = class RabbitMqService { async startMicroService() { const queue = await utils.microServiceName(); const app = await core_1.NestFactory.createMicroservice(rabbit_mq_module_1.RabbitMqModule, { transport: microservices_1.Transport.RMQ, options: { urls: [process.env.RABBITMQ_URL], queue: queue, queueOptions: { durable: true, }, noAck: false, }, }); await app.listen(); return app; } constructor() { this.waitAckownledge = {}; this.ackAttached = false; if (!process.env.RABBITMQ_URL) return; this.startMicroService(); utils.microServiceName().then(projectName => { this.projectName = projectName; this.amqpConnection = new nestjs_rabbitmq_1.AmqpConnection({ exchanges: [ { name: rabbitMQutils.HAKU_SCI_EXCHANGE, type: 'topic', } ], uri: process.env.RABBITMQ_URL, }); }); } get ackQueueName() { return `${this.projectName}_${rabbitMQutils.ACK_QUEUE}`; } async dispatchMessage(messagePattern, userId, id, payload = {}, requireAck = false) { const options = { headers: { userId: userId, id: id }, correlationId: null }; let p; if (requireAck) { if (!this.ackAttached) { this.ackAttached = true; await this.amqpConnection.channel.assertQueue(this.ackQueueName, { durable: true }); this.amqpConnection.channel.consume(this.ackQueueName, async (message) => { const ackMessage = JSON.parse(message.content.toString()); this.updateAck(ackMessage.properties.correlationId); this.amqpConnection.channel.ack(message); }); } options.headers["replyTo"] = this.ackQueueName; options.correlationId = Date.now().toString(); ; const response = await axios_1.default.get(`${process.env.RABBITMQ_API_URL}/bindings`, { auth: rabbitMqApiAuth }); let countExpectedAcknowledged = response.data.filter((binding) => binding.source === rabbitMQutils.HAKU_SCI_EXCHANGE && binding.routing_key === messagePattern).length; p = new Promise((resolve, reject) => { this.waitAckownledge[options.correlationId] = { count: countExpectedAcknowledged, resolve: resolve, reject: reject }; }); p = utils.withWatchdog(p, 10000); } ; await this.amqpConnection.publish(rabbitMQutils.HAKU_SCI_EXCHANGE, messagePattern, payload, options); return p; } sendAck(message) { this.amqpConnection.publish('', message.properties.headers.replyTo, message); } updateAck(correlationId) { if (this.waitAckownledge[correlationId]) { this.waitAckownledge[correlationId].count--; if (this.waitAckownledge[correlationId].count == 0) { this.waitAckownledge[correlationId].resolve(); delete this.waitAckownledge[correlationId]; } } } }; exports.RabbitMqService = RabbitMqService; exports.RabbitMqService = RabbitMqService = __decorate([ (0, common_1.Injectable)(), __metadata("design:paramtypes", []) ], RabbitMqService); function HakuSubscribe(options) { return function (target, key, descriptor) { const originalMethod = descriptor.value; descriptor.value = async function (...args) { const message = args[1]; try { await originalMethod.apply(this, args); } catch (error) { message.properties.headers["error"] = error; } finally { if (message.properties.headers.replyTo) { try { await this.moduleRef.get(RabbitMqService).sendAck(message); } catch (e) { console.log(e); } } ; } }; utils.microServiceName().then((projectName) => { (0, nestjs_rabbitmq_1.RabbitSubscribe)({ routingKey: options.routingKey, exchange: rabbitMQutils.HAKU_SCI_EXCHANGE, queue: projectName, })(target, key, descriptor); }); }; } //# sourceMappingURL=rabbit-mq.service.js.map