forked from Open-Cap-Stack/opencap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.js
76 lines (71 loc) · 1.97 KB
/
db.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
// utils/db.js
const mongoose = require('mongoose');
async function connectDB() {
try {
if (mongoose.connection.readyState === 0) {
const conn = await mongoose.connect(process.env.MONGO_URI || 'mongodb://localhost:27017/opencap_test', {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
useCreateIndex: true,
// Add timeouts to prevent hanging connections
serverSelectionTimeoutMS: 5000,
connectTimeoutMS: 10000,
socketTimeoutMS: 45000,
});
console.log('MongoDB Connected...');
return conn;
}
return mongoose.connection;
} catch (err) {
console.error('MongoDB connection error:', err);
// Ensure connection is closed on error
if (mongoose.connection.readyState !== 0) {
await mongoose.connection.close();
}
process.exit(1);
}
}
async function disconnectDB() {
try {
if (mongoose.connection.readyState !== 0) {
await Promise.race([
mongoose.connection.close(),
new Promise((_, reject) =>
setTimeout(() => reject(new Error('Connection close timeout')), 5000)
)
]);
console.log('MongoDB Disconnected...');
}
} catch (err) {
console.error('MongoDB disconnection error:', err);
// Force close if normal close fails
if (mongoose.connection.readyState !== 0) {
mongoose.connection.destroy();
}
}
}
async function clearDB() {
try {
if (process.env.NODE_ENV === 'test') {
const collections = mongoose.connection.collections;
const clearPromises = Object.values(collections).map(collection =>
collection.deleteMany({})
);
await Promise.all(clearPromises);
}
} catch (err) {
console.error('Error clearing database:', err);
throw err;
}
}
// Add cleanup handler for process termination
process.on('SIGTERM', async () => {
await disconnectDB();
process.exit(0);
});
module.exports = {
connectDB,
disconnectDB,
clearDB
};