From 6f4ae4798b1f9f45890579efdc71786228c234ad Mon Sep 17 00:00:00 2001 From: Behzad Rabiei <53224485+Behzad-rabiei@users.noreply.github.com> Date: Tue, 19 Nov 2024 12:04:38 +0200 Subject: [PATCH 1/2] feat: add connection class --- package.json | 2 +- src/service/connetion.ts | 55 ++++++++++++++++++++++++++++++++++ src/service/databaseManager.ts | 27 ----------------- src/service/index.ts | 4 +-- 4 files changed, 58 insertions(+), 30 deletions(-) create mode 100644 src/service/connetion.ts diff --git a/package.json b/package.json index 61eda86..0f7624f 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@togethercrew.dev/db", - "version": "3.0.73", + "version": "3.0.75", "description": "All interactions with DB", "main": "./dist/index.js", "types": "./dist/index.d.ts", diff --git a/src/service/connetion.ts b/src/service/connetion.ts new file mode 100644 index 0000000..8456312 --- /dev/null +++ b/src/service/connetion.ts @@ -0,0 +1,55 @@ +import mongoose, { type Connection } from 'mongoose'; + +export default class MongoConnectionManager { + private mongoConnection: Connection | null = null; + + public async connect(url: string): Promise { + try { + if (this.mongoConnection !== null) { + throw new Error('MongoDB connection already exists'); + } + await mongoose.connect(url); + this.mongoConnection = mongoose.connection; + console.log('Connected to MongoDB!'); + } catch (error: unknown) { + const errorMessage = error instanceof Error ? error.message : 'Unknown error'; + console.error(`Failed to connect to MongoDB: ${errorMessage}`); + throw new Error(`Failed to connect to MongoDB: ${errorMessage}`); + } + } + + public async disconnect(): Promise { + try { + if (this.mongoConnection !== null) { + await mongoose.disconnect(); + this.mongoConnection = null; + console.log('Disconnected from MongoDB'); + } else { + console.warn('No active MongoDB connection to disconnect.'); + } + } catch (error: unknown) { + const errorMessage = error instanceof Error ? error.message : 'Unknown error'; + console.error(`Failed to disconnect from MongoDB: ${errorMessage}`); + throw new Error(`Failed to disconnect from MongoDB: ${errorMessage}`); + } + } + + /** + * Ensures that there is an active MongoDB connection. + * Throws an error if no connection is active. + */ + public ensureConnected(): void { + if (this.mongoConnection !== null) { + throw new Error('No active MongoDB connection. Please connect before performing database operations.'); + } + } + + /** + * Gets the current MongoDB connection. + * @returns The Mongoose Connection object. + */ + public getConnection(): Connection | null { + this.ensureConnected(); + return this.mongoConnection; + } +} diff --git a/src/service/databaseManager.ts b/src/service/databaseManager.ts index edab662..1c5c9d6 100644 --- a/src/service/databaseManager.ts +++ b/src/service/databaseManager.ts @@ -21,33 +21,6 @@ import { type Snowflake } from 'discord.js'; export default class DatabaseManager { private static instance: DatabaseManager; private modelCache: Record = {}; - private mongoConnection: mongoose.Connection | null = null; - - public async connectToMongoDB(url: string): Promise { - try { - if (this.mongoConnection !== null) { - throw new Error('MongoDB connection already exists'); - } - await mongoose.connect(url); - this.mongoConnection = mongoose.connection; - console.log('Connected to MongoDB!'); - } catch (error) { - console.log({ error }, 'Failed to connect to MongoDB!'); - throw new Error(`Failed to connect to MongoDB: ${error instanceof Error ? error.message : 'Unknown error'}`); - } - } - - public async disconnectFromMongoDB(): Promise { - try { - if (this.mongoConnection !== null) { - await this.mongoConnection.close(); - this.mongoConnection = null; - console.log('Disconnected from MongoDB'); - } - } catch (error) { - throw new Error(`Failed to disconnect from MongoDB: ${error instanceof Error ? error.message : 'Unknown error'}`); - } - } public static getInstance(): DatabaseManager { if (typeof DatabaseManager.instance === 'undefined') { diff --git a/src/service/index.ts b/src/service/index.ts index 3448b8d..cc605fa 100644 --- a/src/service/index.ts +++ b/src/service/index.ts @@ -1,3 +1,3 @@ import DatabaseManager from './databaseManager'; - -export { DatabaseManager }; +import Connetion from './connetion'; +export { DatabaseManager, Connetion }; From c490a303b2bb06009d3c70ab5e38a54acc87d180 Mon Sep 17 00:00:00 2001 From: Behzad Rabiei <53224485+Behzad-rabiei@users.noreply.github.com> Date: Tue, 19 Nov 2024 12:14:53 +0200 Subject: [PATCH 2/2] refactor: clean the MongoConnectionManager --- src/service/connetion.ts | 25 ++++++++++++++++--------- 1 file changed, 16 insertions(+), 9 deletions(-) diff --git a/src/service/connetion.ts b/src/service/connetion.ts index 8456312..80049f8 100644 --- a/src/service/connetion.ts +++ b/src/service/connetion.ts @@ -1,8 +1,23 @@ import mongoose, { type Connection } from 'mongoose'; +/** + * Manages the MongoDB connection using Mongoose. + * Implements the singleton pattern to ensure a single connection throughout the application. + */ export default class MongoConnectionManager { + private static instance: MongoConnectionManager; private mongoConnection: Connection | null = null; + // Private constructor to prevent direct instantiation + private constructor() {} + + public static getInstance(): MongoConnectionManager { + if (typeof MongoConnectionManager.instance === 'undefined') { + MongoConnectionManager.instance = new MongoConnectionManager(); + } + return MongoConnectionManager.instance; + } + public async connect(url: string): Promise { try { if (this.mongoConnection !== null) { @@ -34,20 +49,12 @@ export default class MongoConnectionManager { } } - /** - * Ensures that there is an active MongoDB connection. - * Throws an error if no connection is active. - */ public ensureConnected(): void { - if (this.mongoConnection !== null) { + if (this.mongoConnection === null) { throw new Error('No active MongoDB connection. Please connect before performing database operations.'); } } - /** - * Gets the current MongoDB connection. - * @returns The Mongoose Connection object. - */ public getConnection(): Connection | null { this.ensureConnected(); return this.mongoConnection;