aux-broker-mq
Version:
Микросервис тест взаимодействия
152 lines • 6.67 kB
JavaScript
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.BrokerProxy = void 0;
const amqplib_1 = require("amqplib");
class BrokerProxy {
constructor(config) {
this.config = config;
this.queue = [];
this.exchanges = [];
}
connect() {
return __awaiter(this, void 0, void 0, function* () {
this.connection = yield (0, amqplib_1.connect)("amqp://" + this.config.host);
this.channel = yield this.connection.createChannel();
console.log("[*] Доступно подключение rebbitmq");
});
}
/**
* В случае использования подтверждения сообщений onAck параметр
* будет определять размер предворительной выборки
* @param n количество сообщений
*/
prefetch(n = 1) {
var _a;
return __awaiter(this, void 0, void 0, function* () {
(_a = this.channel) === null || _a === void 0 ? void 0 : _a.prefetch(n);
});
}
createChannel(queue, durable = false) {
var _a;
return __awaiter(this, void 0, void 0, function* () {
if (this.queue.findIndex((r) => r === queue) !== -1)
return;
this.queue.push(queue);
yield ((_a = this.channel) === null || _a === void 0 ? void 0 : _a.assertQueue(queue, {
durable: durable,
}));
});
}
createExchange(name, type, durable = false) {
var _a;
return __awaiter(this, void 0, void 0, function* () {
if (~this.exchanges.findIndex((r) => r === name))
return;
this.exchanges.push(name);
yield ((_a = this.channel) === null || _a === void 0 ? void 0 : _a.assertExchange(name, type, {
durable: durable,
}));
});
}
/**
* Отправляет в брокер сообщений событие
* @param queue Имя очереди
* @param msg сообщение
* @returns успех
*/
emit(queue, msg) {
var _a, _b;
if (Buffer.isBuffer(msg)) {
return !!((_a = this.channel) === null || _a === void 0 ? void 0 : _a.sendToQueue(queue, msg));
}
return !!((_b = this.channel) === null || _b === void 0 ? void 0 : _b.sendToQueue(queue, Buffer.from(JSON.stringify(msg))));
}
publish(exchange, routingKey, msg) {
var _a, _b;
if (Buffer.isBuffer(msg)) {
return !!((_a = this.channel) === null || _a === void 0 ? void 0 : _a.publish(exchange, routingKey, msg));
}
return !!((_b = this.channel) === null || _b === void 0 ? void 0 : _b.publish(exchange, routingKey, Buffer.from(JSON.stringify(msg))));
}
bind(exchange, routingKey, durable = false) {
var _a, _b;
return __awaiter(this, void 0, void 0, function* () {
const q = yield ((_a = this.channel) === null || _a === void 0 ? void 0 : _a.assertQueue("", {
exclusive: true,
durable: durable,
}));
if (!(q === null || q === void 0 ? void 0 : q.queue))
throw new Error("Not have queue");
(_b = this.channel) === null || _b === void 0 ? void 0 : _b.bindQueue(q === null || q === void 0 ? void 0 : q.queue, exchange, routingKey);
return this.on(q.queue);
});
}
/**
* Создаёт подписку на очередь
* @param queue Очередь
* @returns объект с возможностью подписаться через subscribe
*/
on(queue) {
return {
subscribe: (fn) => {
var _a;
(_a = this.channel) === null || _a === void 0 ? void 0 : _a.consume(queue, (msg) => {
if (msg == null)
return fn === null || fn === void 0 ? void 0 : fn();
try {
fn === null || fn === void 0 ? void 0 : fn(JSON.parse(msg.content.toString("utf8")));
}
catch (ex) {
// TODO - Сделать отправку в логгер ошибок
console.error(ex, msg);
}
}, {
noAck: true,
});
},
};
}
/**
* Создаёт синхронную подписку на очередь
* @param queue Очередь
* @returns объект с возможностью подписаться через subscribe
*/
onAck(queue) {
return {
subscribe: (fn) => {
var _a;
(_a = this.channel) === null || _a === void 0 ? void 0 : _a.consume(queue, (msg) => __awaiter(this, void 0, void 0, function* () {
var _b, _c;
if (msg == null)
return fn === null || fn === void 0 ? void 0 : fn();
try {
const success = yield (fn === null || fn === void 0 ? void 0 : fn(JSON.parse(msg.content.toString("utf8"))));
if (success) {
(_b = this.channel) === null || _b === void 0 ? void 0 : _b.ack(msg);
}
else {
(_c = this.channel) === null || _c === void 0 ? void 0 : _c.nack(msg);
}
}
catch (ex) {
// TODO - Сделать отправку в логгер ошибок
console.error(ex, msg);
}
}), {
noAck: false,
});
},
};
}
}
exports.BrokerProxy = BrokerProxy;
//# sourceMappingURL=BrokerProxy.js.map