@@ -4,57 +4,66 @@ import app from '../src/app';
44
55const MONGODB_URI = process . env . MONGO_URI ;
66
7- let isConnected = false ;
7+ let connectionPromise : Promise < void > | null = null ;
88
99async function connectDB ( ) {
10- if ( isConnected && mongoose . connection . readyState === 1 ) {
11- console . log ( 'Using existing MongoDB connection' ) ;
10+ if ( mongoose . connection . readyState === 1 ) {
1211 return ;
1312 }
1413
14+ if ( mongoose . connection . readyState !== 0 ) {
15+ await mongoose . disconnect ( ) ;
16+ connectionPromise = null ;
17+ }
18+
19+ if ( connectionPromise ) {
20+ return connectionPromise ;
21+ }
22+
1523 if ( ! MONGODB_URI ) {
1624 throw new Error ( 'MONGO_URI is not set in environment variables' ) ;
1725 }
1826
19- try {
20- console . log ( 'Creating new MongoDB connection...' ) ;
21-
22- await mongoose . connect ( MONGODB_URI , {
23- bufferCommands : false ,
24- maxPoolSize : 10 ,
25- serverSelectionTimeoutMS : 5000 ,
26- socketTimeoutMS : 45000 ,
27- } ) ;
27+ connectionPromise = ( async ( ) => {
28+ try {
29+ await mongoose . connect ( MONGODB_URI , {
30+ maxPoolSize : 10 ,
31+ minPoolSize : 2 ,
32+ maxIdleTimeMS : 30000 ,
33+ serverSelectionTimeoutMS : 5000 ,
34+ socketTimeoutMS : 45000 ,
35+ } ) ;
2836
29- isConnected = true ;
30- console . log ( 'MongoDB connected successfully' ) ;
37+ mongoose . connection . on ( 'error' , ( err ) => {
38+ console . error ( 'MongoDB connection error:' , err ) ;
39+ connectionPromise = null ;
40+ } ) ;
3141
32- mongoose . connection . on ( 'error ' , ( err ) => {
33- console . error ( 'MongoDB connection error:' , err ) ;
34- isConnected = false ;
35- } ) ;
42+ mongoose . connection . on ( 'disconnected ' , ( ) => {
43+ console . log ( 'MongoDB disconnected' ) ;
44+ connectionPromise = null ;
45+ } ) ;
3646
37- mongoose . connection . on ( 'disconnected' , ( ) => {
38- console . log ( 'MongoDB disconnected' ) ;
39- isConnected = false ;
40- } ) ;
47+ } catch ( error ) {
48+ console . error ( 'Failed to connect to MongoDB:' , error ) ;
49+ connectionPromise = null ;
50+ throw error ;
51+ }
52+ } ) ( ) ;
4153
42- } catch ( error ) {
43- console . error ( 'Failed to connect to MongoDB:' , error ) ;
44- isConnected = false ;
45- throw error ;
46- }
54+ return connectionPromise ;
4755}
4856
57+ connectDB ( ) . catch ( console . error ) ;
58+
4959app . use ( async ( req , res , next ) => {
5060 try {
5161 await connectDB ( ) ;
5262 next ( ) ;
5363 } catch ( error : any ) {
54- console . error ( 'Database connection error:' , error ) ;
5564 res . status ( 500 ) . json ( {
5665 error : 'Database connection failed' ,
57- details : process . env . NODE_ENV === 'development' ? error . message : undefined
66+ message : error . message
5867 } ) ;
5968 }
6069} ) ;
0 commit comments