@@ -7,6 +7,7 @@ import type { AdapterFactory, QueueConfig, QueueManagerConfig, RetryConfig } fro
77class QueueManagerSingleton {
88 #defaultAdapter! : string
99 #adapters: Record < string , AdapterFactory > = { }
10+ #adapterInstances: Map < string , Adapter > = new Map ( )
1011 #globalRetryConfig?: RetryConfig
1112 #queueConfigs: Map < string , QueueConfig > = new Map ( )
1213
@@ -15,6 +16,8 @@ class QueueManagerSingleton {
1516
1617 this . #validateConfig( config )
1718
19+ this . #adapterInstances. clear ( )
20+
1821 this . #defaultAdapter = config . default
1922 this . #adapters = config . adapters
2023 this . #globalRetryConfig = config . retry
@@ -35,16 +38,24 @@ class QueueManagerSingleton {
3538 adapter = this . #defaultAdapter
3639 }
3740
38- const adapterInstance = this . #adapters[ adapter ]
41+ // Return cached instance if exists
42+ const cached = this . #adapterInstances. get ( adapter )
43+ if ( cached ) {
44+ return cached
45+ }
46+
47+ const adapterFactory = this . #adapters[ adapter ]
3948
40- if ( ! adapterInstance ) {
49+ if ( ! adapterFactory ) {
4150 throw new errors . E_CONFIGURATION_ERROR ( [ `Adapter "${ adapter } " is not registered` ] )
4251 }
4352
4453 debug ( 'using adapter "%s"' , adapter )
4554
4655 try {
47- return adapterInstance ( )
56+ const instance = adapterFactory ( )
57+ this . #adapterInstances. set ( adapter , instance )
58+ return instance
4859 } catch ( error ) {
4960 // TODO: Improve error handling
5061 throw new Error ( )
@@ -98,10 +109,11 @@ class QueueManagerSingleton {
98109 }
99110
100111 async destroy ( ) {
101- for ( const adapterName in this . #adapters ) {
102- const adapter = this . #adapters [ adapterName ] ( )
112+ for ( const [ name , adapter ] of this . #adapterInstances ) {
113+ debug ( 'destroying adapter "%s"' , name )
103114 await adapter . destroy ( )
104115 }
116+ this . #adapterInstances. clear ( )
105117 }
106118}
107119
0 commit comments