UNPKG

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