简体   繁体   中英

NestJS - how to provide services of dynamic modules

I'm struggling to figure out on how to provide services from DynamicModule to regular Modules. Pseudocode below:

app.module.ts

@Global()
@Module({
  imports: [
    DynamicModule.forRoot(config),
    RegularModule,
  ],
  providers: [],
  exports: [],
})
export class AppModule {}

dynamic.module.ts

@Module({})
export class DynamicModule implements OnModuleInit, OnModuleDestroy {
  constructor(private dynamicService: dynamicService) {}

  static forRoot(config: Config): DynamicModule {
    return {
      module: DynamicModule,
      imports: [],
      providers: [
        {
          provide: CONFIG_TOKEN,
          useValue: config,
        },
        DynamicService,
      ],
      exports: [
        DynamicService,
      ],
    };
  }
}

dynamic.service.ts

@Injectable()
export class DynamicService {

  constructor(
    @Inject(CONFIG_TOKEN) private readonly config: Config,
  ) {}
}

regular.module.ts

@Module({
  imports: [],
  providers: [RegularService, DynamicService],
  exports: [RegularService],
})
export class RegularModule {}

regular.service.ts

@Injectable()
export class RegularService {

  constructor(
    private readonly dynamicService: DynamicService
  ) {}
}

Providing DynamicService to RegularModule requires to provide CONFIG_TOKEN in RegularModule as well, which seems odd and not practical in case more modules would depend on DynamicService and doesn't seem to be the correct way.

What concepts am I missing and what is correct approach to use services of a DynamicModule?

Would something as forFeature in DynamicModule method would be the right direction?


dynamic modules are modules that need some sort of context defined input, classic example is a database module that would need at least the host url and credentials, which would vary by app.
This means that when the forRoot(input) returns, you have a module just like any regular (non dynamic) module. As such, you can make use of the config value inside the dynamic module's service, export the service on the dynamic module, and then inject that service on other modules that import your dynamic module.
There is no need to also inject the config value on the service that injected the dynamicService .

If you need to have direct access to the config value inside of regularService , and that value is being shared across multiple services and modules, then you should take a look at the ConfigModule and treat that config value as env. If by some very specific reason it cant or should not be in env, then still you should create a separate module for providing this config values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM