@@ -4,36 +4,58 @@ import app from '../src/app';
44
55const MONGODB_URI = process . env . MONGO_URI ;
66
7- let cachedConnection : typeof mongoose | null = null ;
7+ let isConnected = false ;
88
99async function connectDB ( ) {
10- if ( cachedConnection ) {
11- return cachedConnection ;
10+ if ( isConnected && mongoose . connection . readyState === 1 ) {
11+ console . log ( 'Using existing MongoDB connection' ) ;
12+ return ;
1213 }
1314
1415 if ( ! MONGODB_URI ) {
1516 throw new Error ( 'MONGO_URI is not set in environment variables' ) ;
1617 }
1718
18- const conn = await mongoose . connect ( MONGODB_URI , {
19- bufferCommands : false ,
20- } ) ;
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+ } ) ;
28+
29+ isConnected = true ;
30+ console . log ( 'MongoDB connected successfully' ) ;
31+
32+ mongoose . connection . on ( 'error' , ( err ) => {
33+ console . error ( 'MongoDB connection error:' , err ) ;
34+ isConnected = false ;
35+ } ) ;
36+
37+ mongoose . connection . on ( 'disconnected' , ( ) => {
38+ console . log ( 'MongoDB disconnected' ) ;
39+ isConnected = false ;
40+ } ) ;
2141
22- cachedConnection = conn ;
23- return conn ;
42+ } catch ( error ) {
43+ console . error ( 'Failed to connect to MongoDB:' , error ) ;
44+ isConnected = false ;
45+ throw error ;
46+ }
2447}
2548
26- connectDB ( ) . catch ( ( err ) => {
27- console . error ( 'Failed to connect to MongoDB:' , err ) ;
28- } ) ;
29-
3049app . use ( async ( req , res , next ) => {
3150 try {
3251 await connectDB ( ) ;
3352 next ( ) ;
34- } catch ( error ) {
53+ } catch ( error : any ) {
3554 console . error ( 'Database connection error:' , error ) ;
36- res . status ( 500 ) . json ( { error : 'Database connection failed' } ) ;
55+ res . status ( 500 ) . json ( {
56+ error : 'Database connection failed' ,
57+ details : process . env . NODE_ENV === 'development' ? error . message : undefined
58+ } ) ;
3759 }
3860} ) ;
3961
0 commit comments