From bb191da9f63011594905dc8a15be32c85f09cb79 Mon Sep 17 00:00:00 2001 From: Foxix Date: Mon, 7 Jul 2025 20:39:52 +0300 Subject: [PATCH] fix db close leak --- src/db.js | 49 +++++++++++++++++++++++++++++++++++++++++++--- src/routes/auth.js | 2 -- 2 files changed, 46 insertions(+), 5 deletions(-) diff --git a/src/db.js b/src/db.js index d6645b4..8354155 100644 --- a/src/db.js +++ b/src/db.js @@ -9,14 +9,29 @@ if (!uri) { let client; 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 (!global._mongoClientPromise) { - client = new MongoClient(uri); + client = new MongoClient(uri, clientOptions); global._mongoClientPromise = client.connect(); } clientPromise = global._mongoClientPromise; } else { - client = new MongoClient(uri); + client = new MongoClient(uri, clientOptions); clientPromise = client.connect(); } @@ -25,4 +40,32 @@ async function getDb() { 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); +}); diff --git a/src/routes/auth.js b/src/routes/auth.js index 166abc1..40777e8 100644 --- a/src/routes/auth.js +++ b/src/routes/auth.js @@ -186,8 +186,6 @@ router.post('/login', async (req, res) => { } const valid = await bcrypt.compare(password, user.password); if (!valid) return res.status(400).json({ error: 'Invalid password' }); - - const payload = { id: user._id.toString(), email: user.email,