rankery
rankery

Reputation: 317

NestJS TypeORM Imports solution

Is there any good solution for this example?

Seems like if I have a lot of modules like photo.module.ts I need to import DatabaseModule in every feature module.

Tried to put it in app.module.ts but it doesn't help. Maybe there are some solutions with forRoot static import?

Upvotes: 2

Views: 10460

Answers (1)

Kim Kern
Kim Kern

Reputation: 60357

As it says in the docs:

In this article, you'll learn how to create a DatabaseModule based on the TypeORM package from scratch using custom providers mechanism. As a consequence, this solution contains a lot of overhead that you can omit using ready to use and available out-of-the-box dedicated @nestjs/typeorm package.

So better use the @nestjs/typeorm package, see docs.


When you use the @nestjs/typeorm package, you have to import TypeOrmModule.forFeature([PhotoEntity]) for each feature module. In each feature module, you only want to register the entities that belong to that feature. This improves the encapsulation.

You tried to register a module in the AppModule and wondered why its providers weren't available in the feature modules. Note that a module always has to import a module itself so that it can access its exported providers. The only exception to this are global modules. When you annotate a module with the decorator @Global() then it will automatically be imported in all modules as long as it is imported at least once (e.g. in your AppModule).

Upvotes: 5

Related Questions