1
1
import { Pool , PoolClient } from 'pg' ;
2
2
import Config from '../config' ;
3
+ import logger from '../utils/logger' ;
3
4
export class ConnectionPool {
4
5
private _pool : Pool ;
5
6
private _isProduction : 'development' | 'production' ;
@@ -8,19 +9,30 @@ export class ConnectionPool {
8
9
this . _isProduction = Config . environment ;
9
10
this . _pool = this . initializePool ( connectionString ) ;
10
11
}
11
- async connect ( ) : Promise < void > {
12
+ async connect ( ) : Promise < boolean > {
12
13
try {
13
14
const client = await this . _pool . connect ( ) ;
14
- client . release ( ) ; // Connection successful
15
+ client . release ( ) ;
16
+ logger . info ( 'Database connection successful' ) ;
17
+ return true ;
15
18
} catch ( error : any ) {
16
19
console . error ( 'Database connection error:' , error . message ) ;
17
20
if ( error . code === '3D000' ) {
18
21
console . log ( `Database does not exist. Creating database ${ Config . database . databaseName } ...` ) ;
19
22
await this . createDatabase ( ) ;
20
23
await this . reinitializePool ( ) ;
21
- await this . _pool . connect ( ) ;
24
+ try {
25
+ const client = await this . _pool . connect ( ) ;
26
+ client . release ( ) ;
27
+ logger . info ( 'Database connection successful after reinitialization' ) ;
28
+ return true ;
29
+ } catch ( reconnectError : any ) {
30
+ console . error ( 'Reconnection failed:' , reconnectError . message ) ;
31
+ return false ;
32
+ }
22
33
} else {
23
34
console . error ( 'Unexpected error connecting to the database:' , error ) ;
35
+ return false ;
24
36
}
25
37
}
26
38
}
@@ -56,8 +68,8 @@ export class ConnectionPool {
56
68
connectionString,
57
69
ssl : this . _isProduction === 'production' ? { rejectUnauthorized : false } : false ,
58
70
max : 20 ,
59
- idleTimeoutMillis : 10000 ,
60
- connectionTimeoutMillis : 5000 ,
71
+ idleTimeoutMillis : 30000 , // Increase idle timeout
72
+ connectionTimeoutMillis : 10000 , // Increase connection timeout
61
73
keepAlive : true ,
62
74
} ) ;
63
75
}
0 commit comments