Skip to content

feat: add connetion support for repos #203

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

Merged
merged 2 commits into from
May 7, 2025
Merged

Conversation

Behzad-rabiei
Copy link
Member

@Behzad-rabiei Behzad-rabiei commented May 7, 2025

Summary by CodeRabbit

  • Refactor
    • Repository classes now require a database connection when instantiated, enabling more flexible and dynamic usage.
    • Singleton repository exports were replaced with factory functions for greater control over repository instances.
    • Improved type safety and lean query results in repository methods.
    • Enhanced concurrency safety and error handling in database management.
  • Chores
    • Updated linting configuration and added a script for automated code formatting.
    • Improved type-only imports for better code clarity.
    • Removed an outdated changelog entry.

Copy link

coderabbitai bot commented May 7, 2025

Walkthrough

This update refactors repository classes to accept Mongoose Connection objects and exposes factory functions for repository instantiation instead of singleton instances. It improves type safety and model caching in database management, enhances ESLint and package scripts, and removes default exports in favor of named or factory exports. Type-only imports are standardized across files.

Changes

File(s) Change Summary
.eslintrc.json, package.json ESLint config updated to disable specific TypeScript rules; package script lint added for ESLint auto-fix.
CHANGELOG.md Removed the changelog entry for version 3.6.0.
src/connection.ts Refined singleton management, added URI tracking, improved connection logic and error handling.
src/databaseManager.ts Enhanced type safety and concurrency in model caching, improved error handling, and updated singleton typing.
src/interfaces/Module.interface.ts Switched to type-only imports for improved type clarity.
src/repositories/announcement.repository.ts, src/repositories/community.repository.ts,
src/repositories/module.repository.ts, src/repositories/platform.repository.ts,
src/repositories/token.repository.ts, src/repositories/user.repository.ts
Changed imports to type-only; removed default exports, retaining only named exports.
src/repositories/base.repository.ts Introduced strong typing for pagination, improved method signatures for type safety, added findOne, ensured lean query results.
src/repositories/channel.repository.ts, src/repositories/guildMember.repository.ts,
src/repositories/heatMap.repository.ts, src/repositories/memberActivity.repository.ts,
src/repositories/rawInfo.repository.ts, src/repositories/role.repository.ts
Refactored constructors to accept Connection objects; replaced singleton exports with factory functions for dynamic instantiation.
src/repositories/index.ts Updated exports to provide factory functions instead of singleton repository instances.

Sequence Diagram(s)

sequenceDiagram
    participant App
    participant ConnMgr as MongoConnectionManager
    participant DBMgr as DatabaseManager
    participant RepoFactory as Repository Factory
    participant Repo as Repository

    App->>ConnMgr: connect(uri)
    ConnMgr-->>App: Connection instance
    App->>DBMgr: setupModels(connection, dbType)
    DBMgr-->>App: Models ready
    App->>RepoFactory: makeXRepository(connection)
    RepoFactory-->>App: Repository instance
    App->>Repo: Use repository methods
Loading

Possibly related PRs

  • 201 extend mongolib #202: Introduced repository classes as singletons with direct model injection; this PR refactors those to use connection-based instantiation and factory functions.
  • feat: add connection class #180: Added the MongoConnectionManager singleton for MongoDB connections; this PR further refines its logic and typing.

Poem

A hop and a leap, the code takes new form,
Repositories now crafted, connection the norm.
No more singletons, factories abound,
Type safety and clarity happily found.
With models and maps, the cache is now tight—
The rabbit approves: the future is bright!
🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this 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

@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: 1

🔭 Outside diff range comments (6)
src/repositories/user.repository.ts (1)

6-12: 🛠️ Refactor suggestion

Consider refactoring to use Connection parameter for consistency.

According to the PR objectives, this change aims to add connection support for repositories. However, the UserRepository still uses a singleton pattern rather than accepting a Mongoose Connection object and using a factory function for instantiation.

For consistency with other repositories being refactored in this PR, consider updating this class to:

  1. Accept a Connection parameter in the constructor
  2. Use a factory function for instantiation instead of directly exporting a singleton
-export class UserRepository extends BaseRepository<IUser> {
-  constructor(model: Model<IUser> = User) {
+export class UserRepository extends BaseRepository<IUser> {
+  constructor(model: Model<IUser>) {
     super(model);
   }
 }

-export const userRepository = new UserRepository();
+export const createUserRepository = (connection: Connection): UserRepository => {
+  const model = connection.model<IUser>('User', User.schema);
+  return new UserRepository(model);
+};
src/repositories/token.repository.ts (1)

6-12: 🛠️ Refactor suggestion

Consider refactoring to use Connection parameter for consistency.

According to the PR objectives, this change aims to add connection support for repositories. However, the TokenRepository still uses a singleton pattern rather than accepting a Mongoose Connection object and using a factory function for instantiation.

For consistency with other repositories being refactored in this PR, consider updating this class to:

  1. Accept a Connection parameter in the constructor
  2. Use a factory function for instantiation instead of directly exporting a singleton
-export class TokenRepository extends BaseRepository<IToken> {
-  constructor(model: Model<IToken> = Token) {
+export class TokenRepository extends BaseRepository<IToken> {
+  constructor(model: Model<IToken>) {
     super(model);
   }
 }

-export const tokenRepository = new TokenRepository();
+export const createTokenRepository = (connection: Connection): TokenRepository => {
+  const model = connection.model<IToken>('Token', Token.schema);
+  return new TokenRepository(model);
+};
src/repositories/platform.repository.ts (1)

6-12: 🛠️ Refactor suggestion

Consider refactoring to use Connection parameter for consistency.

According to the PR objectives, this change aims to add connection support for repositories. However, the PlatformRepository still uses a singleton pattern rather than accepting a Mongoose Connection object and using a factory function for instantiation.

For consistency with other repositories being refactored in this PR, consider updating this class to:

  1. Accept a Connection parameter in the constructor
  2. Use a factory function for instantiation instead of directly exporting a singleton
-export class PlatformRepository extends BaseRepository<IPlatform> {
-  constructor(model: Model<IPlatform> = Platform) {
+export class PlatformRepository extends BaseRepository<IPlatform> {
+  constructor(model: Model<IPlatform>) {
     super(model);
   }
 }

-export const platformRepository = new PlatformRepository();
+export const createPlatformRepository = (connection: Connection): PlatformRepository => {
+  const model = connection.model<IPlatform>('Platform', Platform.schema);
+  return new PlatformRepository(model);
+};
src/repositories/announcement.repository.ts (1)

6-12: 🛠️ Refactor suggestion

Consider refactoring to use Connection parameter for consistency.

According to the PR objectives, this change aims to add connection support for repositories. However, the AnnouncementRepository still uses a singleton pattern rather than accepting a Mongoose Connection object and using a factory function for instantiation.

For consistency with other repositories being refactored in this PR, consider updating this class to:

  1. Accept a Connection parameter in the constructor
  2. Use a factory function for instantiation instead of directly exporting a singleton
-export class AnnouncementRepository extends BaseRepository<IAnnouncement> {
-  constructor(model: Model<IAnnouncement> = Announcement) {
+export class AnnouncementRepository extends BaseRepository<IAnnouncement> {
+  constructor(model: Model<IAnnouncement>) {
     super(model);
   }
 }

-export const announcementRepository = new AnnouncementRepository();
+export const createAnnouncementRepository = (connection: Connection): AnnouncementRepository => {
+  const model = connection.model<IAnnouncement>('Announcement', Announcement.schema);
+  return new AnnouncementRepository(model);
+};
src/repositories/module.repository.ts (1)

6-13: 🛠️ Refactor suggestion

Repository implementation inconsistent with PR objectives

The ModuleRepository is still being exported as a singleton instance rather than a factory function that accepts a Mongoose Connection. Based on the PR summary, other repositories were refactored to use factory functions for improved connection handling.

Consider refactoring to align with the connection support pattern:

 export class ModuleRepository extends BaseRepository<IModule> {
-  constructor(model: Model<IModule> = Module) {
+  constructor(model: Model<IModule>) {
     super(model);
   }
 }

-export const moduleRepository = new ModuleRepository();
+export const createModuleRepository = (
+  connection?: Connection
+): ModuleRepository => {
+  const model = connection ? connection.model<IModule>('Module') : Module;
+  return new ModuleRepository(model);
+};
src/repositories/community.repository.ts (1)

6-13: 🛠️ Refactor suggestion

Repository implementation inconsistent with PR objectives

Similar to the ModuleRepository, the CommunityRepository is still being exported as a singleton instance rather than a factory function that accepts a Mongoose Connection. This appears inconsistent with the PR's objective of adding connection support for repositories.

Consider refactoring to align with the connection support pattern:

 export class CommunityRepository extends BaseRepository<ICommunity> {
-  constructor(model: Model<ICommunity> = Community) {
+  constructor(model: Model<ICommunity>) {
     super(model);
   }
 }

-export const communityRepository = new CommunityRepository();
+export const createCommunityRepository = (
+  connection?: Connection
+): CommunityRepository => {
+  const model = connection ? connection.model<ICommunity>('Community') : Community;
+  return new CommunityRepository(model);
+};
🧹 Nitpick comments (3)
package.json (1)

1-69: Consider updating package version

Given the significant changes to the repository pattern in this PR (adding connection support), you might want to consider if this warrants a version bump in the package.json.

src/repositories/base.repository.ts (2)

62-64: Consider improving updateOne return type

Currently, updateOne returns any. Consider using Mongoose's UpdateWriteOpResult for better type safety.

-  async updateOne(filter: FilterQuery<T>, update: UpdateQuery<T>, options?: QueryOptions): Promise<any> {
+  async updateOne(filter: FilterQuery<T>, update: UpdateQuery<T>, options?: QueryOptions): Promise<mongoose.UpdateWriteOpResult> {

66-68: Consider improving delete methods return types

The deleteOne and deleteMany methods return any. Consider using Mongoose's DeleteResult for better type safety.

-  async deleteOne(filter: FilterQuery<T>): Promise<any> {
+  async deleteOne(filter: FilterQuery<T>): Promise<mongoose.DeleteResult> {

-  async deleteMany(filter: FilterQuery<T>): Promise<any> {
+  async deleteMany(filter: FilterQuery<T>): Promise<mongoose.DeleteResult> {

Also applies to: 70-72

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between cd326f2 and 0db838e.

📒 Files selected for processing (20)
  • .eslintrc.json (1 hunks)
  • CHANGELOG.md (0 hunks)
  • package.json (1 hunks)
  • src/connection.ts (1 hunks)
  • src/databaseManager.ts (2 hunks)
  • src/interfaces/Module.interface.ts (1 hunks)
  • src/repositories/announcement.repository.ts (1 hunks)
  • src/repositories/base.repository.ts (2 hunks)
  • src/repositories/channel.repository.ts (1 hunks)
  • src/repositories/community.repository.ts (1 hunks)
  • src/repositories/guildMember.repository.ts (1 hunks)
  • src/repositories/heatMap.repository.ts (1 hunks)
  • src/repositories/index.ts (1 hunks)
  • src/repositories/memberActivity.repository.ts (1 hunks)
  • src/repositories/module.repository.ts (1 hunks)
  • src/repositories/platform.repository.ts (1 hunks)
  • src/repositories/rawInfo.repository.ts (1 hunks)
  • src/repositories/role.repository.ts (1 hunks)
  • src/repositories/token.repository.ts (1 hunks)
  • src/repositories/user.repository.ts (1 hunks)
💤 Files with no reviewable changes (1)
  • CHANGELOG.md
🧰 Additional context used
🧬 Code Graph Analysis (7)
src/repositories/rawInfo.repository.ts (2)
src/repositories/base.repository.ts (1)
  • BaseRepository (31-78)
src/interfaces/RawInfo.interface.ts (1)
  • IRawInfo (4-19)
src/repositories/role.repository.ts (2)
src/repositories/base.repository.ts (1)
  • BaseRepository (31-78)
src/interfaces/Role.interface.ts (1)
  • IRole (4-9)
src/repositories/channel.repository.ts (2)
src/repositories/base.repository.ts (1)
  • BaseRepository (31-78)
src/interfaces/Channel.interface.ts (1)
  • IChannel (11-18)
src/repositories/guildMember.repository.ts (2)
src/repositories/base.repository.ts (1)
  • BaseRepository (31-78)
src/interfaces/GuildMember.interface.ts (1)
  • IGuildMember (4-16)
src/repositories/heatMap.repository.ts (2)
src/repositories/base.repository.ts (1)
  • BaseRepository (31-78)
src/interfaces/HeatMap.interface.ts (1)
  • IHeatMap (4-19)
src/repositories/memberActivity.repository.ts (2)
src/repositories/base.repository.ts (1)
  • BaseRepository (31-78)
src/interfaces/MemberActivity.interface.ts (1)
  • IMemberActivity (3-25)
src/databaseManager.ts (7)
src/interfaces/HeatMap.interface.ts (1)
  • IHeatMap (4-19)
src/models/schemas/index.ts (6)
  • heatMapSchema (16-16)
  • MemberActivitySchema (18-18)
  • rawInfoSchema (17-17)
  • guildMemberSchema (19-19)
  • channelSchema (20-20)
  • roleSchema (21-21)
src/interfaces/MemberActivity.interface.ts (1)
  • IMemberActivity (3-25)
src/interfaces/RawInfo.interface.ts (1)
  • IRawInfo (4-19)
src/interfaces/GuildMember.interface.ts (1)
  • IGuildMember (4-16)
src/interfaces/Channel.interface.ts (1)
  • IChannel (11-18)
src/interfaces/Role.interface.ts (1)
  • IRole (4-9)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: ci / build-push / Build + Push Image
🔇 Additional comments (52)
src/repositories/user.repository.ts (1)

1-1: Good use of TypeScript's type imports.

Adding the type modifier to import statements for Model and IUser is a good practice as it clearly indicates these imports are only used for type annotations and not at runtime.

Also applies to: 3-3

src/repositories/token.repository.ts (1)

1-1: Good use of TypeScript's type imports.

Adding the type modifier to import statements for Model and IToken improves type safety by clearly indicating these imports are only used for type annotations and not at runtime.

Also applies to: 3-3

src/repositories/platform.repository.ts (1)

1-1: Good use of TypeScript's type imports.

Adding the type modifier to import statements for Model and IPlatform improves type safety by clearly indicating these imports are only used for type annotations and not at runtime.

Also applies to: 3-3

src/repositories/announcement.repository.ts (1)

1-1: Good use of TypeScript's type imports.

Adding the type modifier to import statements for Model and IAnnouncement improves type safety by clearly indicating these imports are only used for type annotations and not at runtime.

Also applies to: 3-3

src/repositories/module.repository.ts (2)

1-1: Good use of type-only imports

The change to import { type Model } from 'mongoose' correctly identifies this as a type-only import, which is a good TypeScript practice as it ensures this import is only used for type checking and will be removed during compilation.


3-3: Consistent type import pattern

The change to import { type IModule } follows the same pattern of explicitly marking type-only imports, maintaining consistency with the prior change.

src/interfaces/Module.interface.ts (2)

1-1: Good use of type-only imports for Mongoose types

The change to import { type Model, type Types } correctly identifies these as type-only imports, which is good TypeScript practice and aligns with the PR's objective of improving type safety.


3-3: Consistent type-only import pattern

The change to import { type ModuleNames, type PlatformNames } follows the same pattern of explicitly marking type-only imports, maintaining consistency throughout the codebase.

src/repositories/community.repository.ts (2)

1-1: Good use of type-only imports

The change to import { type Model } from 'mongoose' correctly identifies this as a type-only import, which is a good TypeScript practice.


3-3: Consistent type import pattern

The change to import { type ICommunity } follows the same pattern of explicitly marking type-only imports, maintaining consistency with the prior change.

package.json (1)

14-15: Good addition of linting script

Adding the lint script with the --fix option is a good practice as it allows automated fixing of linting issues. The comma added to the previous line is also correct for proper JSON syntax.

.eslintrc.json (3)

6-6: LGTM: Array formatting change

The extended ESLint configurations are now formatted on a single line, which improves readability for this short array.


14-19: Good rule choices to support the repository pattern refactor

These TypeScript ESLint rule disablements align perfectly with the codebase refactoring to support connection-based repositories and factory functions. Particularly:

  • Disabling explicit-function-return-type and explicit-module-boundary-types makes factory functions more concise
  • Disabling no-explicit-any allows for flexibility with Mongoose types when needed
  • Disabling interface-name-prefix permits cleaner interface naming without enforcing prefixes

20-20: LGTM: Array formatting change

The ignore patterns are now formatted on a single line, which improves readability for this short array.

src/repositories/role.repository.ts (3)

1-3: Good use of type-only imports

Nice improvement switching to type-only imports for interfaces and removing the direct model import. This better separates the concerns and prevents circular dependencies.


7-8: Great refactor to support connection-based models

The constructor now correctly accepts a Mongoose Connection instead of directly requiring a model instance. This approach:

  1. Improves flexibility by allowing repositories to work with different database connections
  2. Enhances testability by making it easier to provide mock connections
  3. Supports potential multi-tenant scenarios

12-12: Good factory function pattern

The factory function replaces the previous singleton pattern, which is a better practice for dependency injection. This makes the code more modular and testable.

src/repositories/heatMap.repository.ts (3)

1-3: Good use of type-only imports

Nice improvement switching to type-only imports for interfaces and removing the direct model import. This approach reduces tight coupling and prevents circular dependencies.


7-8: Great refactor to support connection-based models

The constructor now correctly accepts a Mongoose Connection instead of directly requiring a model instance. This change:

  1. Allows for dynamic model creation from the specific connection
  2. Prevents model caching issues when multiple connections exist
  3. Enhances modularity and testability

12-12: Good factory function pattern

The factory function is a better practice than the previous singleton approach. This supports dependency injection and makes testing easier by allowing different connections to be provided.

src/repositories/rawInfo.repository.ts (3)

1-3: Good use of type-only imports

Clean improvement switching to type-only imports for interfaces and removing the direct model import. This reduces coupling between the repository and the actual model implementation.


7-8: Great refactor to support connection-based models

The constructor now correctly accepts a Mongoose Connection instead of directly requiring a model instance. This approach:

  1. Makes the repository more flexible and reusable across different database connections
  2. Improves model caching by obtaining models from the specific connection
  3. Supports better separation of concerns

12-12: Good factory function pattern

The factory function pattern is a strong improvement over singleton instances. This change makes the codebase more maintainable and testable by clearly showing dependencies and enabling isolated testing.

src/repositories/channel.repository.ts (3)

1-3: Good use of type-only imports

The use of type keyword for imports that are only needed for TypeScript type checking is a good practice. It signals to the compiler that these imports are for type checking only and can be safely removed during compilation.


7-8: Well-implemented connection-based model retrieval

The refactoring to accept a Connection object instead of a direct model instance is a good architectural improvement. This approach allows for:

  • More flexible database connection management
  • Better separation of concerns
  • Support for multiple database connections when needed
  • Improved testability with easier mocking

12-12: Good use of factory pattern

The factory function pattern is appropriate here as it:

  • Encapsulates the repository creation logic
  • Provides a clear API for creating repository instances
  • Allows the caller to control when and with which connection a repository is created
  • Makes dependency injection easier in the services that use this repository
src/repositories/memberActivity.repository.ts (2)

1-8: Consistent implementation of connection-based repository pattern

The implementation follows the same pattern as the other repository classes, maintaining consistency across the codebase. The connection-based approach correctly obtains the model dynamically via connection.model<IMemberActivity>('MemberActivity'), which is the right approach when working with Mongoose connections.


12-12: Factory function maintains consistent API

The makeMemberActivityRepository factory function provides a consistent API with the other repository modules, which is important for maintaining a cohesive codebase architecture. This pattern makes it clear how repository instances should be created.

src/repositories/index.ts (2)

2-13: Inconsistent repository export pattern

While the repositories for heat map, raw info, member activity, guild member, channel, and role now use factory functions (prefixed with "make"), other repositories (user, token, community, platform, announcement, module) are still exported as instances without the factory pattern.

Is this inconsistency intentional? If all repositories should follow the same pattern, consider refactoring the remaining repositories to use factory functions as well.


19-24: Export names match import pattern

The export names correctly match the imported factory functions, maintaining consistency between imports and exports.

src/repositories/guildMember.repository.ts (2)

1-8: Consistent implementation of the connection-based repository pattern

The refactoring follows the same pattern as the other repository classes, which is good for maintaining consistency across the codebase. The implementation correctly uses the connection to get the GuildMember model.


12-12: Factory function provides flexibility

The makeGuildMemberRepository factory function allows for creating repository instances with specific connections, which provides more flexibility in managing database connections. This is especially useful in scenarios where multiple database connections might be needed (e.g., for testing or supporting multiple tenants).

src/connection.ts (8)

1-1: Type imports improve clarity

The explicit import of Connection type from mongoose provides better type safety when working with connections.


4-5: Good singleton pattern refinement

Making the instance possibly undefined is a better TypeScript practice for lazy initialization of singleton patterns.


7-7: Tracking current URI enhances safety

Adding currentUri tracking is important for preventing connections to multiple different MongoDB instances.


18-22: Improved connection safety

The connection logic now properly prevents connecting to a different URI when a connection is already active, which prevents potential consistency issues and resource leaks.


24-34: Enhanced connection error handling

The connection process now includes better error handling with specific error messages and properly saves the current URI on successful connection.


37-41: Good defensive programming

Adding a pre-check before disconnection prevents unnecessary disconnect attempts and provides helpful warnings.


45-47: Complete state cleanup on disconnect

Resetting currentUri on disconnect ensures consistent state management.


61-65: Improved type safety for getConnection

The non-nullable return type with proper assertion after the explicit connection check improves type safety while maintaining runtime safety.

src/databaseManager.ts (5)

1-12: Improved type imports and maintainability

The ESLint directive and type-only imports enhance code quality and maintainability.


23-25: Enhanced singleton pattern and model caching

The singleton instance refinement and new Map-based promise caching strategy are excellent improvements that better support concurrent operations.


34-38: Consistent database connection methods

The database connection methods now use consistent caching practices, which improves performance.

Also applies to: 40-44


46-70: Robust model setup with promise caching

This is a significant improvement that properly handles concurrent model setup requests and prevents duplicate model registrations. The async IIFE pattern with promise caching is an excellent approach.


72-80: Complete database cleanup

The enhancements to deleteDatabase properly close the connection and clean up the cache entry, preventing memory leaks.

src/repositories/base.repository.ts (7)

1-10: Improved type imports

Using type-only imports for Mongoose types is a good practice that reduces bundle size in the compiled code.


19-30: Better type safety with pagination interfaces

Adding explicit interfaces for PaginateResult and PaginateModel improves type safety and makes the API more predictable.


34-34: Explicit return types for document creation

Updated return types for create and createMany to explicitly use HydratedDocument, which provides better type safety.

Also applies to: 38-38


42-44: Lean documents for better performance

Using .lean() on find operations returns plain JavaScript objects instead of Mongoose documents, which is more efficient when you only need the data without the document methods.

Also applies to: 46-52


54-61: Added findOne method with lean documents

Adding the findOne method with lean document return type completes the repository pattern and is consistent with the other find methods.


62-62: Better return type definitions

The repository methods now have more accurate return types, which improves type safety throughout the codebase.

Also applies to: 66-66, 70-70


74-77: Type-safe pagination implementation

The paginate method implementation now uses proper type casting with the new PaginateModel interface, making it type-safe.

import { BaseRepository } from './base.repository';
import { IPlatform } from '../interfaces';
import { type IPlatform } from '../interfaces';
import Platform from '../models/Platfrom.model';
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 typo in model import path.

There appears to be a typo in the model import path: "Platfrom" instead of "Platform".

-import Platform from '../models/Platfrom.model';
+import Platform from '../models/Platform.model';
📝 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 Platform from '../models/Platfrom.model';
import Platform from '../models/Platform.model';

@Behzad-rabiei Behzad-rabiei merged commit 63dfb92 into main May 7, 2025
3 checks passed
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.

1 participant