-
Notifications
You must be signed in to change notification settings - Fork 132
/
Copy pathpubsub.ts
38 lines (31 loc) · 1.15 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
import { EventEmitter } from 'events';
import { PubSubEngine } from './pubsub-engine';
export interface PubSubOptions {
eventEmitter?: EventEmitter;
}
export class PubSub 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(triggerName: string, payload: any): Promise<void> {
this.ee.emit(triggerName, payload);
return Promise.resolve();
}
public subscribe(triggerName: 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);
}
}