How Can I use
export const { ConfigurableModuleClass, MODULE_OPTIONS_TOKEN } =
new ConfigurableModuleBuilder<ConfigModuleOptions>()
.setFactoryMethodName('createConfigOptions').build();
to provide multiple providers to a dynamic module?
I read this article Providing Providers to Dynamic NestJS Modules. It is just using a thirty party library. I believe since it was published two years ago the ConfigurableModuleBuilder
can achieve this same use case.
So How can I divide the options passed into registerAsync
into several providers?
AuthModule.registerAsync({
imports: [UserModule],
inject: [UserService, ConfigService],
useFactory: (userService: UserService, configService: ConfigService) => ({
userService: userService,
configService
}),
}),
So, for the code snnipet above how can I do the below?
@Inject(USER_SERVICE) private userService: IUserService,
@Inject(CONFIG_SERVICE) private configService: IConfigService,
Module Definition file
export const {
ConfigurableModuleClass,
MODULE_OPTIONS_TOKEN,
OPTIONS_TYPE,
ASYNC_OPTIONS_TYPE,
} = new ConfigurableModuleBuilder<AuthModuleOptions>().build();
What can be done here is you can make the AuthModule
have a @Module()
decorator that looks like the following:
@Module({
providers: [
{
provide: USER_SERVICE,
inject: [MODULE_OPTIONS_TOKEN],
useFactory: (options: AuthModuleOptions) => options.userService
},
{
provide: CONFIG_SERVICE,
inject: [MODULE_OPTIONS_TOKEN],
useFactory: (options: AuthModuleOptions) => options.configService,
}
],
})
export class AuthModules extends ConfigurableModuleClass {}
Do note that doing this will allow other services within the AuthModule
to inject the userServicevia @Inject(USER_SERVICE)
, but it also means that AuthModule
will not be usable without using the forRoot
/forRootAsync
methods.