-
Notifications
You must be signed in to change notification settings - Fork 4
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
Conversation
WalkthroughThis update refactors repository classes to accept Mongoose Changes
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
Possibly related PRs
Poem
✨ Finishing Touches
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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed 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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this 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 suggestionConsider 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 MongooseConnection
object and using a factory function for instantiation.For consistency with other repositories being refactored in this PR, consider updating this class to:
- Accept a Connection parameter in the constructor
- 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 suggestionConsider 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 MongooseConnection
object and using a factory function for instantiation.For consistency with other repositories being refactored in this PR, consider updating this class to:
- Accept a Connection parameter in the constructor
- 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 suggestionConsider 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 MongooseConnection
object and using a factory function for instantiation.For consistency with other repositories being refactored in this PR, consider updating this class to:
- Accept a Connection parameter in the constructor
- 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 suggestionConsider 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 MongooseConnection
object and using a factory function for instantiation.For consistency with other repositories being refactored in this PR, consider updating this class to:
- Accept a Connection parameter in the constructor
- 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 suggestionRepository implementation inconsistent with PR objectives
The
ModuleRepository
is still being exported as a singleton instance rather than a factory function that accepts a MongooseConnection
. 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 suggestionRepository 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 versionGiven 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 typeCurrently,
updateOne
returnsany
. Consider using Mongoose'sUpdateWriteOpResult
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 typesThe
deleteOne
anddeleteMany
methods returnany
. Consider using Mongoose'sDeleteResult
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
📒 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 forModel
andIUser
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 forModel
andIToken
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 forModel
andIPlatform
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 forModel
andIAnnouncement
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 importsThe 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 patternThe 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 typesThe 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 patternThe 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 importsThe 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 patternThe 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 scriptAdding 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 changeThe 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 refactorThese TypeScript ESLint rule disablements align perfectly with the codebase refactoring to support connection-based repositories and factory functions. Particularly:
- Disabling
explicit-function-return-type
andexplicit-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 changeThe 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 importsNice 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 modelsThe constructor now correctly accepts a Mongoose Connection instead of directly requiring a model instance. This approach:
- Improves flexibility by allowing repositories to work with different database connections
- Enhances testability by making it easier to provide mock connections
- Supports potential multi-tenant scenarios
12-12
: Good factory function patternThe 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 importsNice 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 modelsThe constructor now correctly accepts a Mongoose Connection instead of directly requiring a model instance. This change:
- Allows for dynamic model creation from the specific connection
- Prevents model caching issues when multiple connections exist
- Enhances modularity and testability
12-12
: Good factory function patternThe 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 importsClean 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 modelsThe constructor now correctly accepts a Mongoose Connection instead of directly requiring a model instance. This approach:
- Makes the repository more flexible and reusable across different database connections
- Improves model caching by obtaining models from the specific connection
- Supports better separation of concerns
12-12
: Good factory function patternThe 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 importsThe 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 retrievalThe 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 patternThe 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 patternThe 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 APIThe
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 patternWhile 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 patternThe 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 patternThe 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 flexibilityThe
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 clarityThe explicit import of
Connection
type from mongoose provides better type safety when working with connections.
4-5
: Good singleton pattern refinementMaking the instance possibly undefined is a better TypeScript practice for lazy initialization of singleton patterns.
7-7
: Tracking current URI enhances safetyAdding
currentUri
tracking is important for preventing connections to multiple different MongoDB instances.
18-22
: Improved connection safetyThe 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 handlingThe connection process now includes better error handling with specific error messages and properly saves the current URI on successful connection.
37-41
: Good defensive programmingAdding a pre-check before disconnection prevents unnecessary disconnect attempts and provides helpful warnings.
45-47
: Complete state cleanup on disconnectResetting
currentUri
on disconnect ensures consistent state management.
61-65
: Improved type safety for getConnectionThe 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 maintainabilityThe ESLint directive and type-only imports enhance code quality and maintainability.
23-25
: Enhanced singleton pattern and model cachingThe singleton instance refinement and new
Map
-based promise caching strategy are excellent improvements that better support concurrent operations.
34-38
: Consistent database connection methodsThe database connection methods now use consistent caching practices, which improves performance.
Also applies to: 40-44
46-70
: Robust model setup with promise cachingThis 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 cleanupThe 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 importsUsing 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 interfacesAdding explicit interfaces for
PaginateResult
andPaginateModel
improves type safety and makes the API more predictable.
34-34
: Explicit return types for document creationUpdated return types for
create
andcreateMany
to explicitly useHydratedDocument
, which provides better type safety.Also applies to: 38-38
42-44
: Lean documents for better performanceUsing
.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 documentsAdding 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 definitionsThe 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 implementationThe 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'; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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.
import Platform from '../models/Platfrom.model'; | |
import Platform from '../models/Platform.model'; |
Summary by CodeRabbit