-
-
Notifications
You must be signed in to change notification settings - Fork 4.8k
/
EventEmitterMQ.js
63 lines (50 loc) · 1.23 KB
/
EventEmitterMQ.js
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import events from 'events';
const emitter = new events.EventEmitter();
const subscriptions = new Map();
function unsubscribe(channel: string) {
if (!subscriptions.has(channel)) {
//console.log('No channel to unsub from');
return;
}
//console.log('unsub ', channel);
emitter.removeListener(channel, subscriptions.get(channel));
subscriptions.delete(channel);
}
class Publisher {
emitter: any;
constructor(emitter: any) {
this.emitter = emitter;
}
publish(channel: string, message: string): void {
this.emitter.emit(channel, message);
}
}
class Consumer extends events.EventEmitter {
emitter: any;
constructor(emitter: any) {
super();
this.emitter = emitter;
}
subscribe(channel: string): void {
unsubscribe(channel);
const handler = message => {
this.emit('message', channel, message);
};
subscriptions.set(channel, handler);
this.emitter.on(channel, handler);
}
unsubscribe(channel: string): void {
unsubscribe(channel);
}
}
function createPublisher(): any {
return new Publisher(emitter);
}
function createSubscriber(): any {
return new Consumer(emitter);
}
const EventEmitterMQ = {
createPublisher,
createSubscriber,
};
export { EventEmitterMQ };