-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
TopicRouter.ts
51 lines (40 loc) · 1.21 KB
/
TopicRouter.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
import type { Logger } from '@purista/core'
import { initLogger } from '@purista/core'
import type { IncomingMessageFunction } from '../types/index.js'
import { isMatchingTopic } from './isMatchingTopic.impl.js'
export class TopicRouter {
routes = new Map<number, { topic: string; fn: IncomingMessageFunction }>()
logger: Logger
counter = 1
constructor(logger?: Logger) {
const log = logger ?? initLogger()
this.logger = log.getChildLogger({ name: 'TopicRouter' })
}
add(topic: string, fn: IncomingMessageFunction) {
this.counter++
this.routes.set(this.counter, { topic, fn })
this.logger.debug({ topic, count: this.counter }, 'topic added')
return this.counter
}
remove(topic: string | number) {
if (typeof topic === 'number') {
this.routes.delete(topic)
}
}
match(topic: string, id?: number): IncomingMessageFunction[] {
const handler: IncomingMessageFunction[] = []
if (id) {
const entry = this.routes.get(id)
if (entry) {
handler.push(entry.fn)
}
return handler
}
this.routes.forEach((entry) => {
if (isMatchingTopic(topic, entry.topic)) {
handler.push(entry.fn)
}
})
return handler
}
}