Skip to content

Commit 3bc4ebf

Browse files
committed
Fix build issue
1 parent e8061b0 commit 3bc4ebf

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

server/db/connectionManager.ts

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
import mongoose, { Connection } from 'mongoose';
2+
3+
let globalConnection: Connection | null = null;
4+
5+
/**
6+
* Get or create a connection to the global MongoDB database
7+
* This function returns the existing mongoose connection or creates a new one
8+
*/
9+
export async function connectToGlobalModlDb(): Promise<Connection> {
10+
try {
11+
// If we already have a connection and it's ready, return it
12+
if (globalConnection && globalConnection.readyState === 1) {
13+
return globalConnection;
14+
}
15+
16+
// If mongoose is already connected, use the existing connection
17+
if (mongoose.connection.readyState === 1) {
18+
globalConnection = mongoose.connection;
19+
return globalConnection;
20+
}
21+
22+
// If not connected, establish a new connection
23+
const mongoUri = process.env.MONGODB_URI || 'mongodb://localhost:27017/modl-global';
24+
25+
// Set connection options for better timeout handling
26+
const connectionOptions = {
27+
serverSelectionTimeoutMS: 30000, // 30 seconds
28+
socketTimeoutMS: 30000, // 30 seconds
29+
bufferMaxEntries: 0,
30+
bufferCommands: false,
31+
};
32+
33+
await mongoose.connect(mongoUri, connectionOptions);
34+
globalConnection = mongoose.connection;
35+
36+
console.log('✅ Global MongoDB connection established via connectionManager');
37+
return globalConnection;
38+
} catch (error) {
39+
console.error('❌ Failed to connect to global MongoDB:', error);
40+
throw error;
41+
}
42+
}
43+
44+
/**
45+
* Close the global connection
46+
*/
47+
export async function closeGlobalConnection(): Promise<void> {
48+
if (globalConnection) {
49+
await globalConnection.close();
50+
globalConnection = null;
51+
console.log('🔒 Global MongoDB connection closed');
52+
}
53+
}
54+
55+
/**
56+
* Get the current connection status
57+
*/
58+
export function getConnectionStatus(): number {
59+
return globalConnection?.readyState ?? mongoose.connection.readyState;
60+
}

0 commit comments

Comments
 (0)