@tinkoff/pubsub
Version:
Implementation of the publish/subscribe pattern
49 lines (46 loc) • 1.28 kB
JavaScript
import noop from '@tinkoff/utils/function/noop';
const mockLogger = {
debug: noop,
info: noop,
error: noop,
};
const defaultOptions = {
logger: mockLogger,
resultTransform: (res) => {
if (res.length === 1) {
return res[0];
}
return res;
},
};
class PubSub {
constructor(options) {
this.subscribers = new Map();
const opts = { ...defaultOptions, ...options };
this.logger = opts.logger;
this.resultTransform = opts.resultTransform;
}
subscribe(event, fn) {
this.logger.debug('subscribe', event, fn);
let subs = this.subscribers.get(event);
if (subs) {
subs.add(fn);
}
else {
subs = new Set([fn]);
this.subscribers.set(event, subs);
}
return () => subs.delete(fn);
}
publish(event, ...args) {
this.logger.debug('publish', event, args);
const subs = this.subscribers.get(event);
if (subs && subs.size) {
const promises = [];
subs.forEach((sub) => promises.push(Promise.resolve(sub(...args))));
return Promise.all(promises).then(this.resultTransform);
}
return Promise.resolve();
}
}
export { PubSub };