From dcaee719d17f9f67d8447440fae0683320f10668 Mon Sep 17 00:00:00 2001 From: "C. Fuhrman" Date: Mon, 10 Mar 2025 15:20:07 -0400 Subject: [PATCH] =?UTF-8?q?Fixes=20#286=20-=20Faire=20un=20vrai=20singleto?= =?UTF-8?q?n=20pour=20la=20connexion=20=C3=A0=20la=20base=20de=20donn?= =?UTF-8?q?=C3=A9es?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- server/app.js | 7 +++++++ server/config/db.js | 39 ++++++++++++++++++++++++++++++++------- 2 files changed, 39 insertions(+), 7 deletions(-) diff --git a/server/app.js b/server/app.js index 32f64b9..938d2f0 100644 --- a/server/app.js +++ b/server/app.js @@ -127,4 +127,11 @@ async function start() { }); } +// Graceful shutdown on SIGINT (Ctrl+C) +process.on('SIGINT', async () => { + console.log('Shutting down...'); + await db.closeConnection(); + process.exit(0); +}); + start(); diff --git a/server/config/db.js b/server/config/db.js index cf492bf..ccc43e7 100644 --- a/server/config/db.js +++ b/server/config/db.js @@ -1,28 +1,53 @@ const { MongoClient } = require('mongodb'); -const dotenv = require('dotenv') +const dotenv = require('dotenv'); dotenv.config(); class DBConnection { - constructor() { this.mongoURI = process.env.MONGO_URI; this.databaseName = process.env.MONGO_DATABASE; + this.client = null; this.connection = null; } + // Connect to the database, but don't reconnect if already connected async connect() { - const client = new MongoClient(this.mongoURI); - this.connection = await client.connect(); + if (this.connection) { + console.log('Using existing MongoDB connection'); + return this.connection; + } + + try { + // Create the MongoClient only if the connection does not exist + this.client = new MongoClient(this.mongoURI); + await this.client.connect(); + this.connection = this.client.db(this.databaseName); + console.log('MongoDB connected'); + return this.connection; + } catch (error) { + console.error('MongoDB connection error:', error); + throw new Error('Failed to connect to MongoDB'); + } } + // Return the current database connection getConnection() { if (!this.connection) { - throw new Error('Connexion MongoDB non établie'); + throw new Error('MongoDB connection not established'); + } + return this.connection; + } + + // Close the MongoDB connection gracefully + async closeConnection() { + if (this.client) { + await this.client.close(); + console.log('MongoDB connection closed'); } - return this.connection.db(this.databaseName); } } +// Exporting the singleton instance const instance = new DBConnection(); -module.exports = instance; \ No newline at end of file +module.exports = instance;