0

我面临NestJS动态模块加载的问题。我有一个父动态模块,它从useFactory. 它还在内部导入少量子模块。该useFactory方法返回实际配置,告诉我们应该加载哪些子模块,但不知何故我无法做到这一点。如何根据父模块异步配置加载内部模块?这是示例:

父选项.ts

import { ModuleMetadata } from '@nestjs/common/interfaces';

interface ActualConfigForChildren {
    child1?: {
        child1Id: string;
    };
    child2?: {
        child2Id: string;
    };
    child3?: {
        child3Id: string;
    };
}

export interface ParentModuleAsyncOptions
  extends Pick<ModuleMetadata, 'imports'> {
  name?: string;
  useFactory?: (
    ...args: any[]
  ) => Promise<ActualConfigForChildren> | ActualConfigForChildren;
  inject?: any[];
}

父模块.ts

import { Module, Global, DynamicModule } from '@nestjs/common';
import { ParentModuleAsyncOptions } from './parent.options';

@Global()
@Module({})
export class ParentModule {

  static forRootAsync(options: ParentModuleAsyncOptions): DynamicModule {
    return {
      module: ParentModule,
      providers: [{
        provide: 'PARENT_MODULE_CONFIG_SERVICE',
        useFactory: options.useFactory,
        inject: options.inject || [],
      }],
      exports: ['PARENT_MODULE_CONFIG_SERVICE'],
      imports: [
        ChildModule1, // I want to import it if child1 config is present
        ChildModule2, // I want to import it if child2 config is present
        ChildModule3, // similarly
      ],
    };
  }
}

app.module.ts(我实际导入父模块的地方)

@Module({
    imports: [
      ParentModule.forRootAsync({
        useFactory: (/* Assume I'll make use of ConfigService here */) => ({
            child1: {
                child1Id: '123'
            },
            child2: {
                child2Id: '123'
            },
            child3: {
                child3Id: '123'
            }
        })
      }),
    ],
  })
export class AppModule {}

尽管子模块可以访问PARENT_MODULE_CONFIG_SERVICE ,但我根本不希望它们加载。

4

0 回答 0