@@ -5,6 +5,8 @@ export class ConnectionPool {
55 private _pool : Pool ;
66 private _isProduction : 'development' | 'production' ;
77 private _isClosed : boolean = false ;
8+ private _isReinitializing : boolean = false ;
9+
810 constructor ( ) {
911 const connectionString = this . getConnectionString ( ) ;
1012 this . _isProduction = Config . environment ;
@@ -83,22 +85,29 @@ export class ConnectionPool {
8385 if ( this . _isClosed ) {
8486 throw new Error ( 'Cannot reinitialize a closed pool.' ) ;
8587 }
86-
87- if ( this . _pool && ! this . _pool . ended ) {
88- logger . warn ( 'Ending the current pool before reinitialization...' ) ;
89- await this . _pool . end ( ) ;
88+ if ( this . _isReinitializing ) {
89+ logger . warn ( 'Reinitialization already in progress. Waiting...' ) ;
90+ await new Promise ( ( resolve ) => setTimeout ( resolve , 2000 ) ) ;
91+ return ;
9092 }
9193
92- const newConnectionString = this . getConnectionString ( ) ;
93- this . _pool = this . initializePool ( newConnectionString ) ;
94-
94+ this . _isReinitializing = true ;
9595 try {
96+ if ( this . _pool && ! this . _pool . ended ) {
97+ logger . warn ( 'Ending the current pool before reinitialization...' ) ;
98+ await this . _pool . end ( ) ;
99+ }
100+
101+ const newConnectionString = this . getConnectionString ( ) ;
102+ this . _pool = this . initializePool ( newConnectionString ) ;
96103 const testClient = await this . _pool . connect ( ) ;
97- testClient . release ( ) ; // Ensure the new pool is functional
104+ testClient . release ( ) ;
98105 logger . info ( 'Connection pool reinitialized successfully.' ) ;
99106 } catch ( err : any ) {
100107 logger . error ( 'Failed to reinitialize connection pool:' , err . message ) ;
101108 throw err ; // Let the caller handle this failure
109+ } finally {
110+ this . _isReinitializing = false ;
102111 }
103112 }
104113}
0 commit comments