2024-09-28 17:29:21 -04:00
|
|
|
import { MongoClient, Db } from 'mongodb';
|
|
|
|
|
import dotenv from 'dotenv';
|
2024-03-29 20:08:34 -04:00
|
|
|
|
|
|
|
|
dotenv.config();
|
|
|
|
|
|
|
|
|
|
class DBConnection {
|
2024-09-28 17:29:21 -04:00
|
|
|
private mongoURI: string;
|
|
|
|
|
private databaseName: string;
|
|
|
|
|
private connection: MongoClient | null;
|
2024-03-29 20:08:34 -04:00
|
|
|
|
|
|
|
|
constructor() {
|
2024-09-28 17:29:21 -04:00
|
|
|
this.mongoURI = process.env.MONGO_URI || '';
|
|
|
|
|
this.databaseName = process.env.MONGO_DATABASE || '';
|
2024-03-29 20:08:34 -04:00
|
|
|
this.connection = null;
|
|
|
|
|
}
|
|
|
|
|
|
2024-09-28 17:29:21 -04:00
|
|
|
async connect(): Promise<void> {
|
2024-03-29 20:08:34 -04:00
|
|
|
const client = new MongoClient(this.mongoURI);
|
|
|
|
|
this.connection = await client.connect();
|
|
|
|
|
}
|
|
|
|
|
|
2024-09-28 17:29:21 -04:00
|
|
|
getConnection(): Db {
|
2024-03-29 20:08:34 -04:00
|
|
|
if (!this.connection) {
|
|
|
|
|
throw new Error('Connexion MongoDB non établie');
|
|
|
|
|
}
|
|
|
|
|
return this.connection.db(this.databaseName);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2024-09-28 17:29:21 -04:00
|
|
|
export default DBConnection;
|