-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathbus_manager.ts
More file actions
72 lines (57 loc) · 2.04 KB
/
Copy pathbus_manager.ts
File metadata and controls
72 lines (57 loc) · 2.04 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
/**
* @boringnode/bus
*
* @license MIT
* @copyright BoringNode
*/
import { RuntimeException } from '@poppinss/utils/exceptions'
import { Bus } from './bus.js'
import debug from './debug.js'
import type {
ManagerConfig,
Serializable,
SubscribeHandler,
TransportConfig,
} from './types/main.js'
export class BusManager<KnownTransports extends Record<string, TransportConfig>> {
readonly #defaultTransportName: keyof KnownTransports | undefined
readonly #transports: KnownTransports
#transportsCache: Partial<Record<keyof KnownTransports, Bus>> = {}
constructor(config: ManagerConfig<KnownTransports>) {
debug('creating bus manager. config: %O', config)
this.#transports = config.transports
this.#defaultTransportName = config.default
}
use<KnownTransport extends keyof KnownTransports>(transports?: KnownTransport): Bus {
let transportToUse: keyof KnownTransports | undefined = transports || this.#defaultTransportName
if (!transportToUse) {
throw new RuntimeException(
'Cannot create bus instance. No default transport is defined in the config'
)
}
const cachedTransport = this.#transportsCache[transportToUse]
if (cachedTransport) {
debug('returning cached transport instance for %s', transportToUse)
return cachedTransport
}
const transportConfig = this.#transports[transportToUse]
debug('creating new transport instance for %s', transportToUse)
const transportInstance = new Bus(transportConfig.transport(), {
retryQueue: transportConfig.retryQueue,
})
this.#transportsCache[transportToUse] = transportInstance
return transportInstance
}
async publish(channel: string, message: Serializable) {
return this.use().publish(channel, message)
}
async subscribe<T extends Serializable>(channel: string, handler: SubscribeHandler<T>) {
return await this.use().subscribe(channel, handler)
}
async unsubscribe(channel: string) {
return await this.use().unsubscribe(channel)
}
disconnect() {
return this.use().disconnect()
}
}