UNPKG

1.24 kBJavaScriptView Raw
1import { Repeater } from '@repeaterjs/repeater';
2import { CustomEvent, EventTarget } from '@whatwg-node/events';
3/**
4 * Utility for publishing and subscribing to events.
5 */
6export const createPubSub = (config) => {
7 const target = config?.eventTarget ??
8 new EventTarget();
9 return {
10 publish(routingKey, ...args) {
11 const payload = args[1] ?? args[0];
12 const topic = args[1] === undefined
13 ? routingKey
14 : `${routingKey}:${args[0]}`;
15 const event = new CustomEvent(topic, {
16 detail: payload,
17 });
18 target.dispatchEvent(event);
19 },
20 subscribe(...[routingKey, id]) {
21 const topic = id === undefined ? routingKey : `${routingKey}:${id}`;
22 return new Repeater(function subscriptionRepeater(next, stop) {
23 stop.then(function subscriptionRepeaterStopHandler() {
24 target.removeEventListener(topic, pubsubEventListener);
25 });
26 target.addEventListener(topic, pubsubEventListener);
27 function pubsubEventListener(event) {
28 next(event.detail);
29 }
30 });
31 },
32 };
33};