标签: nest-dynamic-modules

Nest js 将模块从 forRoot 转换为 forRootAsync

@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

6
推荐指数
1
解决办法
2971
查看次数

从动态模块选项创建提供者数组

我正在使用 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)

typescript nestjs nestjs-providers nest-dynamic-modules

5
推荐指数
0
解决办法
327
查看次数