UNPKG

reservease.consumer

Version:

This package allows you to create an amqplib consumer and producer.

89 lines (88 loc) 3.64 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.RabitQueue = void 0; const amqplib = require("amqplib"); const InternalApiResponse_1 = require("./InternalApiResponse"); class RabitQueue { constructor(messageQueueUrl) { this._connectionUrl = messageQueueUrl; } async CreateQueueChannel(queue) { try { const connection = await amqplib.connect(this._connectionUrl); const channel = await connection.createChannel(); await channel.assertQueue(queue, { durable: false }); return new InternalApiResponse_1.InternalApiResponse(true, channel, 'Successfully created channel'); } catch (err) { return new InternalApiResponse_1.InternalApiResponse(false, undefined, err?.message); } } async CreateExchangeChannel(exchangeName) { try { const connection = await amqplib.connect(this._connectionUrl); const channel = await connection.createChannel(); await channel.assertExchange(exchangeName, 'direct', { durable: true }); return new InternalApiResponse_1.InternalApiResponse(true, channel, 'Successfully created channel'); } catch (err) { return new InternalApiResponse_1.InternalApiResponse(false, undefined, err?.message); } } async SentToQueue(channel, queue, message) { try { await channel.assertQueue(queue, { durable: false }); await channel.sendToQueue(queue, Buffer.from(message), { persistent: true, }); return new InternalApiResponse_1.InternalApiResponse(true, message, `[x] Sent ${message}`); } catch (err) { return new InternalApiResponse_1.InternalApiResponse(false, message, ` [x] Failed to send '%s' ${message} to queue ${queue}`, err?.message); } } async ConsumeFromQueue(channel, queue, service) { try { const q = await channel.assertQueue(queue, { durable: false, }); channel.consume(q.queue, (msg) => { if (msg.content) { service.SubscribeEvents(msg.content.toString()); } }, { noAck: true, }); } catch (err) { throw err; } } async SubscribeMessage(channel, exchangeName, bindingKey, service) { try { await channel.assertExchange(exchangeName, 'direct', { durable: true }); const q = await channel.assertQueue('', { exclusive: true }); channel.bindQueue(q.queue, exchangeName); channel.consume(q.queue, (msg) => { if (msg.content) { service.SubscribeEvents(msg.content.toString()); } }, { noAck: true, }); } catch (error) { throw error; } } async PublishMessage(channel, exchangeName, bindingKey, message) { try { channel.publish(exchangeName, bindingKey, Buffer.from(message)); return new InternalApiResponse_1.InternalApiResponse(true, message, `Published message to exchange name: ${exchangeName} successfully`); } catch (error) { return new InternalApiResponse_1.InternalApiResponse(false, undefined, `Failed to publish message to exchange name: ${exchangeName}`); } } } exports.RabitQueue = RabitQueue;