Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add mongoDb connet function #179

Merged
merged 2 commits into from
Nov 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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.72",
"version": "3.0.73",
"description": "All interactions with DB",
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
Expand Down
32 changes: 27 additions & 5 deletions src/service/databaseManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,32 +21,55 @@ 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'}`);
}
}
Comment on lines +26 to +38
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Add production-ready connection options and improve error handling

While the basic implementation is good, there are several improvements needed for production use:

  1. Remove redundant error logging since you're throwing the error
  2. Add connection options for better reliability
  3. Use loose equality for null check

Apply these changes:

 public async connectToMongoDB(url: string): Promise<void> {
   try {
-    if (this.mongoConnection !== null) {
+    if (this.mongoConnection != null) {
       throw new Error('MongoDB connection already exists');
     }
-    await mongoose.connect(url);
+    await mongoose.connect(url, {
+      useNewUrlParser: true,
+      useUnifiedTopology: true,
+      serverSelectionTimeoutMS: 5000,
+      connectTimeoutMS: 10000,
+    });
     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'}`);
   }
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
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 connectToMongoDB(url: string): Promise<void> {
try {
if (this.mongoConnection != null) {
throw new Error('MongoDB connection already exists');
}
await mongoose.connect(url, {
useNewUrlParser: true,
useUnifiedTopology: true,
serverSelectionTimeoutMS: 5000,
connectTimeoutMS: 10000,
});
this.mongoConnection = mongoose.connection;
console.log('Connected to MongoDB!');
} catch (error) {
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'}`);
}
}

// Singleton pattern to get the instance of DatabaseManager
public static getInstance(): DatabaseManager {
if (typeof DatabaseManager.instance === 'undefined') {
DatabaseManager.instance = new DatabaseManager();
}
return DatabaseManager.instance;
}

// Method to get Guild Database connection
public async getGuildDb(guildId: Snowflake): Promise<Connection> {
const dbName = guildId;
const db = mongoose.connection.useDb(dbName, { useCache: true });
await this.setupModels(db, 'guild');
return db;
}

// Method to get Platform Database connection
public async getPlatformDb(platformId: string): Promise<Connection> {
const dbName = platformId;
const db = mongoose.connection.useDb(dbName, { useCache: true });
await this.setupModels(db, 'platform');
return db;
}

// Method to setup models based on database type
private async setupModels(db: Connection, dbType: 'guild' | 'platform'): Promise<void> {
if (!this.modelCache[db.name]) {
try {
Expand All @@ -66,7 +89,6 @@ export default class DatabaseManager {
}
}

// Method to delete a database using the connection
public async deleteDatabase(db: Connection): Promise<void> {
const dbName = db.name;
try {
Expand Down