TypeOrmModule.forRootAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: (config: ConfigService) => ({
type: "postgres",
url: config.get("DATABASE_URL"),
}),
});
A dynamic module is a module whose providers are decided at runtime, not written as fixed metadata. A static method on the module returns a DynamicModule object. This object has module, providers, exports, and optionally imports and global. It extends the module's static metadata.
The method names follow a convention:
forRootconfigures a module once for the whole app.registerconfigures it for one specific consumer. You can call it with different options in different places.forFeaturebuilds on aforRootconfiguration for one feature module. For example,TypeOrmModule.forFeature([User])registers repositories.
The Async variants, like forRootAsync, get their options from other providers, such as ConfigService. They accept useFactory together with inject and imports. They also accept useClass or useExisting. Nest runs the factory first, and the factory may be async. Only then does Nest create the module's providers.
For your own modules, ConfigurableModuleBuilder generates this boilerplate for you.
- A static method returns a
DynamicModuleobject. forRootis used once per app,registeronce per consumer andforFeatureonce per feature.- Async variants use
useFactorywithinjectandimports. - This lets options depend on other providers, like
ConfigService. ConfigurableModuleBuildergenerates the boilerplate.
Read more