@21jumpclick/service-messenger
Version:
Amqp lib to send and receive messages from different applications
82 lines • 2.77 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.Messenger = void 0;
const file_importer_1 = require("./core/file-importer");
const messenger_1 = require("./core/messenger");
const metadata_1 = require("./core/metadata");
class Messenger {
static getInstance() {
if (!Messenger.instance) {
Messenger.instance = new Messenger();
}
return Messenger.instance;
}
constructor() {
if (Messenger.instance) {
throw new Error('Messenger is a singleton');
}
process.once('beforeExit', async () => {
try {
return await this.close();
}
catch (e) {
}
});
}
static init(config) {
Messenger.getInstance().init(config);
}
init(config) {
file_importer_1.FileImporter.import(config.rootDir);
this.config = config;
this.broker = new messenger_1.Broker(config.rabbit, config.name);
this.broker.connect().then(() => {
this.broker.listen(({ key, args, opts }) => metadata_1.MetadataManager.instance().trigger(key, (args === null || args === void 0 ? void 0 : args.data) || args, opts));
});
}
static publish(type, data, options) {
Messenger.getInstance().publish(type, data, options);
}
publish(type, data, options) {
if (this.config.verbose) {
console.log(`Publishing message to ${type} with payload : \n${JSON.stringify({ data }, null, 2)}`);
}
this.broker.publish(type, { data, type }, options);
}
static broadcast(type, data) {
Messenger.getInstance().broadcast(type, data);
}
broadcast(type, data) {
if (this.config.verbose) {
console.log(`Broadcasting message to ${type} with payload : \n${JSON.stringify({ data }, null, 2)}`);
}
this.broker.broadcast(type, { data, type });
}
static invoke(type, data, options) {
return Messenger.getInstance().invoke(type, data, options);
}
async invoke(type, data, options) {
if (this.config.verbose) {
console.log(`Invoking message to ${type} with payload : \n${JSON.stringify({ data }, null, 2)}`);
}
const result = await this.broker.invoke(type, { data, type }, options);
if (result === undefined) {
return null;
}
try {
const json = JSON.parse(result);
return json;
}
catch (e) {
return result;
}
}
static close() {
return Messenger.getInstance().close();
}
close() {
return this.broker.close();
}
}
exports.Messenger = Messenger;
//# sourceMappingURL=event.js.map