@allgemein/eventbus
Version:
101 lines • 3.12 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.EventChannel = void 0;
const lodash_1 = require("lodash");
const Constants_1 = require("../Constants");
class EventChannel {
constructor(nodeId, name, adapter) {
this.remote = true;
this.inc = 0;
this.grouped = false;
this.next = 0;
this.subscriber = [];
this.nodeId = nodeId;
this.name = name;
this.adapter = adapter;
this.grouped = (0, lodash_1.get)(this.adapter.options, 'extra.group', null) != null;
}
getAdapter() {
return this.adapter;
}
get size() {
return this.subscriber.length;
}
callSubscriber(o, obj) {
return new Promise(async (resolve, reject) => {
try {
// @ts-ignore
const res = await o.object[o.method](obj);
resolve(res);
}
catch (err) {
reject(err);
}
});
}
process(obj) {
const prms = [];
// TODO check if not already this class by deserialization
const targetClazz = Reflect.construct(this.adapter.clazz, []);
(0, lodash_1.assign)(targetClazz, obj);
if (this.subscriber.length > 0) {
if (!this.grouped) {
for (const iSubscriber of this.subscriber) {
prms.push(this.callSubscriber(iSubscriber, targetClazz));
}
}
else {
// on grouped, rotate registered subscriber
prms.push(this.callSubscriber(this.subscriber[this.next], targetClazz));
this.next++;
if (this.next >= this.subscriber.length) {
this.next = 0;
}
}
}
return Promise.all(prms);
}
id(uuid) {
return [this.nodeId, this.name, uuid].join('-');
}
async register(subscriber, method, nodeId) {
if (!subscriber[method]) {
throw new Error('method doesn\'t exists in subscriber object');
}
this.subscriber.push({
nodeId: nodeId,
object: subscriber,
method: method
});
if (!this.adapter.isSubscribed()) {
await this.adapter.subscribe(this.process.bind(this));
}
}
unregister(subscriber) {
for (let i = this.subscriber.length - 1; i >= 0; i--) {
if (this.subscriber[i].object === subscriber) {
this.subscriber.splice(i, 1);
}
}
}
post(o, opts) {
const ttl = (0, lodash_1.get)(opts, Constants_1.K_TTL, 1000);
try {
return this.adapter.publish(o).then(x => x.waitForResult(ttl));
}
catch (err) {
if (ttl) {
throw err;
}
else {
return null;
}
}
}
async close() {
this.subscriber = [];
await this.adapter.close();
}
}
exports.EventChannel = EventChannel;
//# sourceMappingURL=EventChannel.js.map