UNPKG

inceptum

Version:

hipages take on the foundational library for enterprise-grade apps written in NodeJS

80 lines 2.93 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const RabbitmqClient_1 = require("./RabbitmqClient"); const RabbitmqConsumerHandlerError_1 = require("./RabbitmqConsumerHandlerError"); class RabbitmqConsumer extends RabbitmqClient_1.RabbitmqClient { constructor(clientConfig, name, consumerConfig, handler) { super(clientConfig, name); this.messageHandler = handler; this.consumerConfig = Object.assign({}, consumerConfig); this.consumerConfig.options = this.consumerConfig.options || {}; } async init() { await super.init(); await this.subscribe(this.consumerConfig.appQueueName, this.consumerConfig.options); } /** * Subscribe to a queue */ async subscribe(queueName, consumeOptions = {}) { return await this.channel.consume(queueName, (message) => { this.handleMessage(message); }, consumeOptions); } async handleMessage(message) { try { await this.messageHandler.handle(message); } catch (e) { const retriesCount = ++message.properties.headers.retriesCount; if (e instanceof RabbitmqConsumerHandlerError_1.RabbitmqConsumerHandlerUnrecoverableError || !this.allowRetry(retriesCount)) { // add to dlq try { this.channel.sendToQueue(this.consumerConfig.dlqName, message.content); } catch (err) { this.logger.error('failed to send message to dlq', err); this.channel.nack(message); } } else { // depending on retries config, retry const ttl = this.getTtl(retriesCount); const options = { expiration: ttl, headers: message.properties.headers, }; try { this.channel.sendToQueue(this.consumerConfig.delayQueueName, message.content, options); } catch (err) { // put message back to rabbitmq this.channel.nack(message); } } } finally { this.channel.ack(message); } } /** * * @param retriesCount number * @reutrn number in milliseconds */ getTtl(retriesCount = 1) { if (this.allowRetry(retriesCount)) { return Math.pow(this.consumerConfig.retryDelayFactor, retriesCount - 1) * this.consumerConfig.retryDelayInMinute * 60 * 1000; } return 0; } allowRetry(retriesCount) { return retriesCount && this.consumerConfig.maxRetries >= retriesCount; } async close() { await super.close(); } } exports.RabbitmqConsumer = RabbitmqConsumer; //# sourceMappingURL=RabbitmqConsumer.js.map