Skip to content

Commit

Permalink
Merge pull request #180 from TogetherCrew/add-connect-to-DB
Browse files Browse the repository at this point in the history
feat: add connection class
  • Loading branch information
Behzad-rabiei authored Nov 19, 2024
2 parents 22e9660 + c490a30 commit 6001eb9
Show file tree
Hide file tree
Showing 4 changed files with 65 additions and 30 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -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",
Expand Down
62 changes: 62 additions & 0 deletions src/service/connetion.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
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<void> {
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<void> {
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}`);
}
}

public ensureConnected(): void {
if (this.mongoConnection === null) {
throw new Error('No active MongoDB connection. Please connect before performing database operations.');
}
}

public getConnection(): Connection | null {
this.ensureConnected();
return this.mongoConnection;
}
}
27 changes: 0 additions & 27 deletions src/service/databaseManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,33 +21,6 @@ import { type Snowflake } from 'discord.js';
export default class DatabaseManager {
private static instance: DatabaseManager;
private modelCache: Record<string, boolean> = {};
private mongoConnection: mongoose.Connection | null = null;

public async connectToMongoDB(url: string): Promise<void> {
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<void> {
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') {
Expand Down
4 changes: 2 additions & 2 deletions src/service/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
import DatabaseManager from './databaseManager';

export { DatabaseManager };
import Connetion from './connetion';
export { DatabaseManager, Connetion };

0 comments on commit 6001eb9

Please sign in to comment.