-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathmemory.ts
More file actions
86 lines (66 loc) · 1.75 KB
/
Copy pathmemory.ts
File metadata and controls
86 lines (66 loc) · 1.75 KB
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/**
* @boringnode/bus
*
* @license MIT
* @copyright BoringNode
*/
import type { Transport, Serializable, SubscribeHandler } from '../types/main.js'
export function memory() {
return () => new MemoryTransport()
}
export class MemoryTransport implements Transport {
#id!: string
/**
* A Map that stores the subscriptions for each channel.
*/
static #subscriptions: Map<
string,
Array<{
handler: SubscribeHandler<any>
busId: string
}>
> = new Map()
setId(id: string) {
this.#id = id
return this
}
/**
* List of messages received by this bus
*/
receivedMessages: any[] = []
async publish(channel: string, message: Serializable) {
const handlers = MemoryTransport.#subscriptions.get(channel)
let count: number = 0
if (!handlers) {
return count
}
for (const { handler, busId } of handlers) {
if (busId === this.#id) continue
count++
handler(message)
}
return count
}
async subscribe<T extends Serializable>(channel: string, handler: SubscribeHandler<T>) {
const handlers = MemoryTransport.#subscriptions.get(channel) || []
handlers.push({ handler: this.#wrapHandler(handler), busId: this.#id })
MemoryTransport.#subscriptions.set(channel, handlers)
}
async unsubscribe(channel: string) {
const handlers = MemoryTransport.#subscriptions.get(channel) || []
MemoryTransport.#subscriptions.set(
channel,
handlers.filter((h) => h.busId !== this.#id)
)
}
async disconnect() {
MemoryTransport.#subscriptions.clear()
}
onReconnect(_callback: () => void) {}
#wrapHandler(handler: SubscribeHandler<any>) {
return (message: any) => {
this.receivedMessages.push(message)
handler(message)
}
}
}