EvalueTonSavoir/server/config/db.ts

31 lines
767 B
TypeScript
Raw Normal View History

import { MongoClient, Db } from 'mongodb';
import dotenv from 'dotenv';
2024-03-29 20:08:34 -04:00
dotenv.config();
class DBConnection {
private mongoURI: string;
private databaseName: string;
private connection: MongoClient | null;
2024-03-29 20:08:34 -04:00
constructor() {
this.mongoURI = process.env.MONGO_URI || '';
this.databaseName = process.env.MONGO_DATABASE || '';
2024-03-29 20:08:34 -04:00
this.connection = null;
}
async connect(): Promise<void> {
2024-03-29 20:08:34 -04:00
const client = new MongoClient(this.mongoURI);
this.connection = await client.connect();
}
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);
}
}
export default DBConnection;