fix db close leak

This commit is contained in:
2025-07-07 20:39:52 +03:00
parent 1be1a7e621
commit bb191da9f6
2 changed files with 46 additions and 5 deletions

View File

@@ -9,14 +9,29 @@ if (!uri) {
let client; let client;
let clientPromise; let clientPromise;
const clientOptions = {
maxPoolSize: 10,
minPoolSize: 0,
serverSelectionTimeoutMS: 5000,
socketTimeoutMS: 45000,
connectTimeoutMS: 30000,
keepAlive: true,
keepAliveInitialDelay: 300000,
retryWrites: true,
w: 'majority',
useNewUrlParser: true,
useUnifiedTopology: true,
tlsAllowInvalidCertificates: true
};
if (process.env.NODE_ENV === 'development') { if (process.env.NODE_ENV === 'development') {
if (!global._mongoClientPromise) { if (!global._mongoClientPromise) {
client = new MongoClient(uri); client = new MongoClient(uri, clientOptions);
global._mongoClientPromise = client.connect(); global._mongoClientPromise = client.connect();
} }
clientPromise = global._mongoClientPromise; clientPromise = global._mongoClientPromise;
} else { } else {
client = new MongoClient(uri); client = new MongoClient(uri, clientOptions);
clientPromise = client.connect(); clientPromise = client.connect();
} }
@@ -25,4 +40,32 @@ async function getDb() {
return _client.db(); return _client.db();
} }
module.exports = { getDb }; async function closeConnection() {
if (client) {
await client.close();
}
}
module.exports = { getDb, closeConnection };
process.on('SIGINT', async () => {
await closeConnection();
process.exit(0);
});
process.on('SIGTERM', async () => {
await closeConnection();
process.exit(0);
});
process.on('uncaughtException', async (err) => {
console.error('Uncaught Exception:', err);
await closeConnection();
process.exit(1);
});
process.on('unhandledRejection', async (reason) => {
console.error('Unhandled Rejection:', reason);
await closeConnection();
process.exit(1);
});

View File

@@ -186,8 +186,6 @@ router.post('/login', async (req, res) => {
} }
const valid = await bcrypt.compare(password, user.password); const valid = await bcrypt.compare(password, user.password);
if (!valid) return res.status(400).json({ error: 'Invalid password' }); if (!valid) return res.status(400).json({ error: 'Invalid password' });
const payload = { const payload = {
id: user._id.toString(), id: user._id.toString(),
email: user.email, email: user.email,