@amirmarmul/waba-common
Version:

99 lines (98 loc) • 3.73 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Event = void 0;
const core_1 = require("../../../../core");
const promises_1 = require("timers/promises");
class Event extends core_1.Event {
correlationId;
constructor(payload) {
super(payload);
this.correlationId = this.uniqueId();
}
setup(channel) {
channel.assertQueue(this.exclusiveQueue, { exclusive: true });
}
publish(options = {}) {
core_1.logger.debug("Publish message %s", this.constructor.name);
return new Promise((resolve) => {
const correlationId = this.correlationId;
const handleMessage = async (msg) => {
if (msg.properties.correlationId == correlationId) {
const parsedMessage = this.parseMessage(msg);
this.channel.removeListener("message", handleMessage);
await this.close();
resolve(parsedMessage);
}
};
this.channel.consume(this.exclusiveQueue, handleMessage, { noAck: true });
this.channel.sendToQueue(this.queue, this.payload, Object.assign({
correlationId: correlationId,
replyTo: this.exclusiveQueue,
deliveryMode: 2,
persistent: true,
}, options));
});
}
publishWithoutPersistence(options = {}) {
core_1.logger.debug("Publish message %s", this.constructor.name);
return new Promise((resolve) => {
const correlationId = this.correlationId;
const handleMessage = async (msg) => {
if (msg.properties.correlationId == correlationId) {
const parsedMessage = this.parseMessage(msg);
this.channel.removeListener("message", handleMessage);
await this.close();
resolve(parsedMessage);
}
};
this.channel.consume(this.exclusiveQueue, handleMessage, { noAck: true });
this.channel.sendToQueue(this.queue, this.payload, Object.assign({
correlationId: correlationId,
replyTo: this.exclusiveQueue,
deliveryMode: 1,
persistent: false,
}, options));
});
}
get queue() {
const queue = [];
queue.push("Rmq");
queue.push("rpc");
queue.push(this.exchange);
queue.push(this.topic);
return queue.join(".");
}
get exclusiveQueue() {
const executiveQueue = [];
executiveQueue.push(this.constructor.name);
executiveQueue.push(this.exchange);
executiveQueue.push(this.topic);
executiveQueue.push(this.correlationId);
return executiveQueue.join(".");
}
uniqueId() {
return String(new core_1.UniqueId());
}
parseMessage(msg) {
const json = msg.content.toString();
return JSON.parse(json);
}
async close() {
return await (0, promises_1.setTimeout)(1000, async () => {
if (this.channel) {
this.channel
.deleteQueue(this.exclusiveQueue)
.then(() => {
core_1.logger.info("The response queue is cleared");
})
.catch((err) => {
core_1.logger.error("Failed to delete queue: ", { msg: err.message });
});
await this.channel.close().catch((reason) => {
core_1.logger.error("Failed to close rpc channel", { reason });
});
}
});
}
}
exports.Event = Event;