This repository has been archived by the owner on Oct 18, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.ts
71 lines (56 loc) · 1.8 KB
/
index.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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import { Logger, Observer } from '../../common/utils';
export class EventBus {
private readonly logger: Logger;
private observers: Map<string, Observer> = new Map();
constructor() {
this.logger = new Logger('@superviz/sdk/event-bus');
this.logger.log('event bus created');
}
/**
* @function subscribe
* @description subscribe to event
* @param event - event name
* @param callback - callback function
* @returns {void}
*/
public subscribe = (event: string, callback: (data: unknown) => void): void => {
this.logger.log('event bus service @ subscribe', { event, callback });
if (!this.observers.has(event)) {
this.observers.set(event, new Observer());
}
this.observers.get(event).subscribe(callback);
};
/**
* @function unsubscribe
* @description - unsubscribe from event
* @param event - event name
* @param callback - callback function
* @returns {void}
*/
public unsubscribe = (event: string, callback: (data: unknown) => void): void => {
this.logger.log('event bus service @ unsubscribe', { event, callback });
if (!this.observers.has(event)) return;
this.observers.get(event).reset();
this.observers.delete(event);
};
/**
* @function publish
* @description - publish event
* @param event - event name
* @param data - data to publish
* @returns {void}
*/
public publish = (event: string, data: unknown): void => {
this.logger.log('event bus service @ publish', { event, data });
if (!this.observers.has(event)) return;
this.observers.get(event).publish(data);
};
public destroy = (): void => {
this.logger.log('event bus service @ destroy');
this.observers.forEach((observer) => {
observer.reset();
observer.destroy();
});
this.observers.clear();
};
}