-
Notifications
You must be signed in to change notification settings - Fork 7
/
index.ts
52 lines (42 loc) · 1.22 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
export class PubSub {
private subscriptions: Map<string, Array<Function>>;
constructor() {
this.subscriptions = new Map<string, Array<Function>>();
}
public subscribe(event: string, callback: Function) {
const subscribers = this.subscriptions.get(event);
if (subscribers) {
subscribers.push(callback);
} else {
this.subscriptions.set(event, [callback]);
}
}
public publish(event: string, ...args: unknown[]) {
for (const callback of this.subscriptions.get(event)) {
callback(...args);
}
}
}
export class UsersService {
public constructor(private readonly emitter: PubSub) {}
public createUser(email: string, password: string) {
// some user creation logic
this.emitter.publish('NEW_USER_EVENT', email);
}
}
export class UsersMetricsService {
public constructor(private readonly emitter: PubSub) {
this.emitter.subscribe('NEW_USER_EVENT', this.onNewUser);
}
public onNewUser(email: string) {
// some metrics logic
}
}
export class NotificationService {
public constructor(private readonly emitter: PubSub) {
this.emitter.subscribe('NEW_USER_EVENT', this.onNewUser);
}
public onNewUser(email: string) {
// some email notification logic
}
}