-
Notifications
You must be signed in to change notification settings - Fork 76
Description
TypeORM Entity Loading Optimization
Here is the issue, translated and formatted for easy copy-pasting into a GitHub or similar tracking system.
Title
TypeORM Entity Loading Optimization: Modularize Configuration to Eliminate Long Entity List in app.module.ts
Description
Currently, our TypeORM configuration centralizes the bulk loading of entities using the entities argument within TypeOrmModule.forRoot(...) inside the app.module.ts file.
As the project grows, this single list of entities has become excessively long and difficult to maintain, negatively impacting the readability and scalability of the main module. This practice goes against NestJS's principle of modularization.
Problem
Maintenance and Readability: The extensive entity list in app.module.ts makes the file verbose, difficult to read, and error-prone when adding or removing new entities.
Violation of Modularity: The core module (AppModule) has direct knowledge of and dependency on all entities in the entire application, which is poor practice for a microservice or modular architecture.
Proposed Solution
We should modularize the TypeORM configuration by moving the entity declaration to their respective feature modules, leveraging TypeOrmModule.forFeature([...]).
This involves the following steps:
Remove the large entities array from TypeOrmModule.forRoot(...) in app.module.ts.
In each feature module (e.g., UsersModule, ProductsModule), import and configure the entities specific to that module:
TypeScript
// users.module.ts
@Module({
imports: [
TypeOrmModule.forFeature([User, Profile]) // Entities are now defined here
],
controllers: [UserController],
providers: [UserService],
exports: [TypeOrmModule] // Optional: if services need the Repository
})
export class UsersModule {}- Alternative Considered (and Rationale)
- Alternative Description Rationale
- Automatic Entity Loading (autoLoadEntities)
- Use the autoLoadEntities: true property in forRoot to let TypeORM automatically discover entities (if file structure is standard). Not
- Recommended as the sole solution. While it cleans the list, modularization with forFeature is the better NestJS pattern.
- It explicitly defines which entities are available within a module's scope, providing better control and clarity.
Tasks
[ ] Remove the entities property from TypeOrmModule.forRoot in app.module.ts.
[ ] Identify all feature modules that own TypeORM entities.
[ ] In each module, add the import of TypeOrmModule.forFeature([Entity1, Entity2, ...]) with its corresponding entities.
[ ] Perform integration tests to ensure all entities are loaded correctly and database operations remain functional.