EvalueTonSavoir/server/config/db.js

53 lines
1.7 KiB
JavaScript
Raw Permalink Normal View History

2024-03-29 20:08:34 -04:00
const { MongoClient } = require('mongodb');
const dotenv = require('dotenv');
2024-03-29 20:08:34 -04:00
dotenv.config();
class DBConnection {
constructor() {
2025-03-14 00:42:49 -04:00
// for testing with @shelf/jest-mongodb
this.mongoURI = globalThis.__MONGO_URI__ || process.env.MONGO_URI;
this.databaseName = globalThis.__MONGO_DB_NAME__ || process.env.MONGO_DATABASE;
this.client = null;
2024-03-29 20:08:34 -04:00
this.connection = null;
2025-03-14 00:42:49 -04:00
console.log(`db.js: Mongo URI: ${this.mongoURI}`);
console.log(`db.js: Mongo DB: ${this.databaseName}`);
2024-03-29 20:08:34 -04:00
}
2025-03-14 00:42:49 -04:00
// Return the current database connection, creating it if necessary
async getConnection() {
if (this.connection) {
console.log('Using existing MongoDB connection');
return this.connection;
}
try {
// Create the MongoClient only if the connection does not exist
2025-03-14 00:42:49 -04:00
this.client = new MongoClient(this.mongoURI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
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');
}
2024-03-29 20:08:34 -04:00
}
// Close the MongoDB connection gracefully
async closeConnection() {
if (this.client) {
await this.client.close();
2025-03-14 00:42:49 -04:00
this.connection = null;
console.log('MongoDB connection closed');
2024-03-29 20:08:34 -04:00
}
}
}
// Exporting the singleton instance
2024-03-29 20:08:34 -04:00
const instance = new DBConnection();
module.exports = instance;