Two new classes have been added: EnvUtils and MongodbService. EnvUtils provides functionality for fetching environment variables and logging them. MongodbService implements connection to MongoDB with user credentials fetched from environment variables. Additionally, some updates have been made to logs.util.ts to improve logging style and biome.json for better code standards adherence.
49 lines
1.2 KiB
TypeScript
49 lines
1.2 KiB
TypeScript
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");
|
|
});
|
|
}
|
|
}
|