import { EnvUtils } from "@utils/env.util"; import { LogsUtils } from "@utils/logs.util"; import { MongoClient } from "mongodb"; export class MongodbService { private envs: EnvUtils; private readonly client: MongoClient; private logs: LogsUtils; constructor(contextName: string) { this.envs = new EnvUtils(`MongoDB >> ${contextName}`); this.logs = new LogsUtils(`MongoDB >> ${contextName}`); try { const uri = `mongodb://${this.envs.get("MONGO_USERNAME")}:${this.envs.get("MONGO_PASSWORD")}@localhost:${this.envs.get("MONGO_PORT")}/`; this.logs.trace("MongoDB URI:", uri); this.client = new MongoClient(uri); } catch (error) { this.logs.error(`Error connecting to MongoDB:`, error); throw new Error(); } } connect() { return this.client .connect() .then(() => { this.logs.info("Connected to MongoDB"); }) .catch((error) => { this.logs.error("Error connecting to MongoDB:", error); //throw error; }); } use() { try { return this.client.db(`${this.envs.get("MONGO_DATABASE")}`); } catch (err) { this.logs.error("Error using MongoDB:", err); throw err; } } close() { this.client.close().then(() => { this.logs.info("Connection to MongoDB closed"); }); } }