@Module({
imports: [],
providers: [SupertokensService, AuthService],
exports: [],
controllers: [AuthController],
})
export class AuthModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer.apply(AuthMiddleware).forRoutes('*');
}
static forRoot({
connectionURI,
apiKey,
appInfo,
}: AuthModuleConfig): DynamicModule {
return {
providers: [
{
useValue: {
appInfo,
connectionURI,
apiKey,
},
provide: ConfigInjectionToken,
},
],
exports: [],
imports: [],
module: AuthModule,
};
}
}
Run Code Online (Sandbox Code Playgroud)
这个实现的问题是我不能使用环境变量,所以我需要useFactory来传递 ConfigService。有人可以这样做吗,并给出一些解释。
authentication node.js node-modules nestjs nest-dynamic-modules
我正在使用 NestJS,正在构建可重用的模块,可通过forRoot
静态forRootAsync
方法进行配置。
我正在寻找一种基于模块选项提供同一类的多个提供程序的方法。
export type MyModuleOptions = {
services: MyServiceOptions[];
}
export type MyServiceOptions = {
name: string;
url: string;
}
Run Code Online (Sandbox Code Playgroud)
基于此选项,通过基本方法很容易实现结果forRoot
:
export class MyModule {
static forRoot(options: MyModuleOptions): DynamicModule {
const providers = options.services.map((service_options) => {
// \__________________/
// loop over the options to generate each provider
return {
provide: 'SERVICE_' + service_options.name,
// \_______________________________/
// generate the provider token based on the options
useFactory: () => {
return new MyService(service_options.url);
}
} …
Run Code Online (Sandbox Code Playgroud)