forked from brendon1982/ts-mocking-exercises
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path06_PubSub.ts
42 lines (33 loc) · 980 Bytes
/
06_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
import { randomInteger } from "../tests-implemented/helpers/random"
type Callback = (...params: any[]) => any
export enum PubSubChannels {
itemUpdated = 'item:updated',
}
export class PubSub {
private static instance: PubSub
private subscriptions: Record<string, Callback[]>
static getInstance() {
if (!this.instance) {
this.instance = new PubSub()
}
return this.instance
}
constructor() {
this.subscriptions = {} as Record<string, Callback[]>
}
async publish(channel: string, payload: unknown) {
console.log(`publishing ${JSON.stringify(payload)} on ${channel}`)
for (const callback of this.subscriptions[channel]) {
setTimeout(() => {
callback(payload)
}, randomInteger(100, 500))
}
}
async subscribe(channel: string, callback: Callback) {
console.log(`subscribing to ${channel}`)
this.subscriptions[channel] = [
...(this.subscriptions[channel] || []),
callback,
]
}
}