-
Notifications
You must be signed in to change notification settings - Fork 132
/
Copy pathpubsub.ts
46 lines (39 loc) · 1.33 KB
/
pubsub.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import { EventEmitter } from 'events';
import { PubSubEngine } from './pubsub-engine';
export interface PubSubOptions {
eventEmitter?: EventEmitter;
}
export class PubSub<
Events extends { [event: string]: unknown } = Record<string, never>
> extends PubSubEngine {
protected ee: EventEmitter;
private subscriptions: { [key: string]: [string, (...args: any[]) => void] };
private subIdCounter: number;
constructor(options: PubSubOptions = {}) {
super();
this.ee = options.eventEmitter || new EventEmitter();
this.subscriptions = {};
this.subIdCounter = 0;
}
public publish<K extends keyof Events>(
triggerName: K & string,
payload: Events[K] extends never ? any : Events[K]
): Promise<void> {
this.ee.emit(triggerName, payload);
return Promise.resolve();
}
public subscribe<K extends keyof Events>(
triggerName: K & string,
onMessage: (...args: any[]) => void
): Promise<number> {
this.ee.addListener(triggerName, onMessage);
this.subIdCounter = this.subIdCounter + 1;
this.subscriptions[this.subIdCounter] = [triggerName, onMessage];
return Promise.resolve(this.subIdCounter);
}
public unsubscribe(subId: number) {
const [triggerName, onMessage] = this.subscriptions[subId];
delete this.subscriptions[subId];
this.ee.removeListener(triggerName, onMessage);
}
}