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 connection class #180

Merged
merged 2 commits into from
Nov 19, 2024
Merged

feat: add connection class #180

merged 2 commits into from
Nov 19, 2024

Conversation

Behzad-rabiei
Copy link
Member

@Behzad-rabiei Behzad-rabiei commented Nov 19, 2024

Summary by CodeRabbit

  • New Features

    • Introduced a new MongoConnectionManager class for improved MongoDB connection management.
    • Added methods for connecting, disconnecting, ensuring connection, and retrieving the current connection.
  • Bug Fixes

    • Removed redundant connection management from the DatabaseManager class, streamlining database operations.
  • Documentation

    • Updated export statements to include the new Connection entity alongside DatabaseManager.
  • Chores

    • Updated package version from "3.0.73" to "3.0.75".

Copy link

coderabbitai bot commented Nov 19, 2024

Caution

Review failed

The pull request is closed.

Walkthrough

The changes in this pull request involve updates to the package.json version number and the introduction of a new MongoConnectionManager class in src/service/connetion.ts for managing MongoDB connections. The DatabaseManager class in src/service/databaseManager.ts has been modified to remove its connection management methods, relying instead on Mongoose's built-in capabilities. Additionally, the src/service/index.ts file has been updated to export the new Connection type along with the existing DatabaseManager.

Changes

File Change Summary
package.json Version updated from "3.0.73" to "3.0.75".
src/service/connetion.ts Added MongoConnectionManager class with methods: getInstance, connect, disconnect, ensureConnected, getConnection.
src/service/databaseManager.ts Removed mongoConnection property and methods: connectToMongoDB, disconnectFromMongoDB.
src/service/index.ts Added import for Connection and updated export statement to include Connection.

Possibly related PRs

  • feat: add mongoDb connet function #179: The changes in package.json for version updates are similar, as both PRs involve a version bump in the same file. Additionally, both PRs modify the DatabaseManager class, but the main PR introduces a new connection management class while the retrieved PR enhances the existing DatabaseManager with connection methods.

Suggested reviewers

  • mehdi-torabiv

🐰 In the garden, connections bloom,
A new manager dispels the gloom.
With Mongo's embrace, we now align,
In code we trust, our paths entwine.
Version updated, progress in sight,
Hopping forward, all feels right! 🌼

Warning

Rate limit exceeded

@Behzad-rabiei has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 18 minutes and 8 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 6f4ae47 and c490a30.


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@mehdi-torabiv mehdi-torabiv left a comment

Choose a reason for hiding this comment

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

well done!

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 6

🧹 Outside diff range and nitpick comments (1)
src/service/connetion.ts (1)

21-35: Add timeout handling to disconnect method

Similar to connect, the disconnect method should handle timeouts and use proper logging.

Here's a suggested improvement:

-  public async disconnect(): Promise<void> {
+  public async disconnect(timeoutMs: number = 5000): Promise<void> {
     try {
       if (this.mongoConnection !== null) {
-        await mongoose.disconnect();
+        await Promise.race([
+          mongoose.disconnect(),
+          new Promise((_, reject) =>
+            setTimeout(() => reject(new Error('Disconnect timeout')), timeoutMs)
+          ),
+        ]);
         this.mongoConnection = null;
-        console.log('Disconnected from MongoDB');
+        // TODO: Replace with proper logger
+        console.log('[MongoDB] Disconnected successfully');
       } else {
-        console.warn('No active MongoDB connection to disconnect.');
+        // TODO: Replace with proper logger
+        console.warn('[MongoDB] No active connection to disconnect');
       }
     } catch (error: unknown) {
       const errorMessage = error instanceof Error ? error.message : 'Unknown error';
-      console.error(`Failed to disconnect from MongoDB: ${errorMessage}`);
+      // TODO: Replace with proper logger
+      console.error(`[MongoDB] Disconnect failed: ${errorMessage}`);
       throw new Error(`Failed to disconnect from MongoDB: ${errorMessage}`);
     }
   }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 22e9660 and 6f4ae47.

📒 Files selected for processing (4)
  • package.json (1 hunks)
  • src/service/connetion.ts (1 hunks)
  • src/service/databaseManager.ts (0 hunks)
  • src/service/index.ts (1 hunks)
💤 Files with no reviewable changes (1)
  • src/service/databaseManager.ts
✅ Files skipped from review due to trivial changes (2)
  • package.json
  • src/service/index.ts

Comment on lines 3 to 55
export default class MongoConnectionManager {
private mongoConnection: Connection | null = null;

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}`);
}
}

/**
* 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;
}
}
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 connection event handlers

The class should listen to important Mongoose connection events to handle disconnections and errors gracefully.

Add this method and call it in the connect method:

private setupConnectionHandlers(): void {
  if (!this.mongoConnection) return;

  this.mongoConnection.on('disconnected', () => {
    // TODO: Replace with proper logger
    console.warn('[MongoDB] Connection lost');
    // Implement reconnection logic if needed
  });

  this.mongoConnection.on('error', (error) => {
    // TODO: Replace with proper logger
    console.error('[MongoDB] Connection error:', error);
  });
}

Call it after establishing the connection:

   this.mongoConnection = mongoose.connection;
+  this.setupConnectionHandlers();
   // TODO: Replace with proper logger

Comment on lines +51 to +54
public getConnection(): Connection | null {
this.ensureConnected();
return this.mongoConnection;
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix return type and behavior mismatch in getConnection

The method declares it can return null but after ensureConnected(), it should never return null.

Here's the fix:

-  public getConnection(): Connection | null {
+  public getConnection(): Connection {
     this.ensureConnected();
-    return this.mongoConnection;
+    // After ensureConnected(), this.mongoConnection is guaranteed to be non-null
+    return this.mongoConnection!;
   }
📝 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 getConnection(): Connection | null {
this.ensureConnected();
return this.mongoConnection;
}
public getConnection(): Connection {
this.ensureConnected();
// After ensureConnected(), this.mongoConnection is guaranteed to be non-null
return this.mongoConnection!;
}

Comment on lines 41 to 45
public ensureConnected(): void {
if (this.mongoConnection !== null) {
throw new Error('No active MongoDB connection. Please connect before performing database operations.');
}
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix critical logic error in ensureConnected method

The condition is reversed! It currently throws an error when a connection exists, which is the opposite of what it should do.

Here's the fix:

   public ensureConnected(): void {
-    if (this.mongoConnection !== null) {
+    if (this.mongoConnection === null) {
       throw new Error('No active MongoDB connection. Please connect before performing database operations.');
     }
   }
📝 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 ensureConnected(): void {
if (this.mongoConnection !== null) {
throw new Error('No active MongoDB connection. Please connect before performing database operations.');
}
}
public ensureConnected(): void {
if (this.mongoConnection === null) {
throw new Error('No active MongoDB connection. Please connect before performing database operations.');
}
}

Comment on lines 1 to 4
import mongoose, { type Connection } from 'mongoose';

export default class MongoConnectionManager {
private mongoConnection: Connection | null = null;
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider implementing singleton pattern

Since database connections should be managed as singletons to prevent multiple connections, consider implementing the singleton pattern for this class.

Here's a suggested implementation:

 import mongoose, { type Connection } from 'mongoose';

 export default class MongoConnectionManager {
+  private static instance: MongoConnectionManager | null = null;
   private mongoConnection: Connection | null = null;
+  
+  private constructor() {}
+  
+  public static getInstance(): MongoConnectionManager {
+    if (!MongoConnectionManager.instance) {
+      MongoConnectionManager.instance = new MongoConnectionManager();
+    }
+    return MongoConnectionManager.instance;
+  }
📝 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
import mongoose, { type Connection } from 'mongoose';
export default class MongoConnectionManager {
private mongoConnection: Connection | null = null;
import mongoose, { type Connection } from 'mongoose';
export default class MongoConnectionManager {
private static instance: MongoConnectionManager | null = null;
private mongoConnection: Connection | null = null;
private constructor() {}
public static getInstance(): MongoConnectionManager {
if (!MongoConnectionManager.instance) {
MongoConnectionManager.instance = new MongoConnectionManager();
}
return MongoConnectionManager.instance;
}

Comment on lines 1 to 55
import mongoose, { type Connection } from 'mongoose';

export default class MongoConnectionManager {
private mongoConnection: Connection | null = null;

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}`);
}
}

/**
* 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;
}
}
Copy link

Choose a reason for hiding this comment

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

💡 Codebase verification

⚠️ Potential issue

Fix filename typo and update affected imports

The filename typo "connetion.ts" needs to be corrected to "connection.ts", and the following changes are required:

  • Rename src/service/connetion.ts to src/service/connection.ts
  • Update import in src/service/index.ts from import Connetion from './connetion' to import Connection from './connection'
  • Update export in src/service/index.ts from Connetion to Connection
🔗 Analysis chain

Fix typo in filename: "connetion.ts" should be "connection.ts"

The filename contains a typo which should be corrected to maintain consistency and prevent confusion.

Let's verify if this typo affects any imports in other files:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for imports referencing this file
rg -l "from ['\"].*connetion['\"]"

Length of output: 61


Script:

#!/bin/bash
# Check the content of the file that imports connetion.ts
cat src/service/index.ts

Length of output: 151

Comment on lines +6 to +19
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}`);
}
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Enhance connection handling with options, timeout, and proper logging

The connection method needs improvements for production readiness:

  1. Missing Mongoose connection options
  2. No connection timeout
  3. No retry mechanism
  4. Direct console.log usage

Here's a suggested implementation:

-  public async connect(url: string): Promise<void> {
+  public async connect(
+    url: string,
+    options: mongoose.ConnectOptions = {},
+    timeoutMs: number = 5000
+  ): Promise<void> {
     try {
       if (this.mongoConnection !== null) {
         throw new Error('MongoDB connection already exists');
       }
-      await mongoose.connect(url);
+      await Promise.race([
+        mongoose.connect(url, {
+          ...options,
+          serverSelectionTimeoutMS: timeoutMs,
+          connectTimeoutMS: timeoutMs,
+        }),
+        new Promise((_, reject) =>
+          setTimeout(() => reject(new Error('Connection timeout')), timeoutMs)
+        ),
+      ]);
       this.mongoConnection = mongoose.connection;
-      console.log('Connected to MongoDB!');
+      // TODO: Replace with proper logger
+      console.log('[MongoDB] Connected successfully');
     } catch (error: unknown) {
       const errorMessage = error instanceof Error ? error.message : 'Unknown error';
-      console.error(`Failed to connect to MongoDB: ${errorMessage}`);
+      // TODO: Replace with proper logger
+      console.error(`[MongoDB] Connection failed: ${errorMessage}`);
       throw new Error(`Failed to connect to MongoDB: ${errorMessage}`);
     }
   }
📝 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 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 connect(
url: string,
options: mongoose.ConnectOptions = {},
timeoutMs: number = 5000
): Promise<void> {
try {
if (this.mongoConnection !== null) {
throw new Error('MongoDB connection already exists');
}
await Promise.race([
mongoose.connect(url, {
...options,
serverSelectionTimeoutMS: timeoutMs,
connectTimeoutMS: timeoutMs,
}),
new Promise((_, reject) =>
setTimeout(() => reject(new Error('Connection timeout')), timeoutMs)
),
]);
this.mongoConnection = mongoose.connection;
// TODO: Replace with proper logger
console.log('[MongoDB] Connected successfully');
} catch (error: unknown) {
const errorMessage = error instanceof Error ? error.message : 'Unknown error';
// TODO: Replace with proper logger
console.error(`[MongoDB] Connection failed: ${errorMessage}`);
throw new Error(`Failed to connect to MongoDB: ${errorMessage}`);
}
}

@Behzad-rabiei Behzad-rabiei merged commit 6001eb9 into main Nov 19, 2024
11 checks passed
@coderabbitai coderabbitai bot mentioned this pull request Nov 19, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants