3

I would like to disable module (or all endpoints and exported services) using environment feature flags. I have a configuration file which looks like this:

{ "featureFlags": { "books": true, "cars": false } }

In my app.module.ts I have the following code.

@Module({
  imports: [
    ConfigModule.forRoot({ load: [config] }),
    BooksModule,
    CarsModule,
  ],
  controllers: [],
  providers: [],
})
export class AppModule {}

Something like this is what I would like to do. Is this possible?

@Module({})
export class CarsModule {
  static forAsync(configService: ConfigService): DynamicModule {
    const controllers = []
    const providers = []
    const exports = []
    if (configService.get("config").featureFlags.cars) {
      controllers.push(...)
      exports.push(...)
      providers.push(...)
    }
    return {
      module: CarsModule,
      controllers,
      providers,
      exports,
    };
  }
}

Alex Wayne
  • 178,991
  • 47
  • 309
  • 337
jm18457
  • 443
  • 1
  • 7
  • 19

1 Answers1

2

Dependency injection is not available in Nest dynamic modules. If you want to use configuration outside Nest's IoC container, you can try nest-typed-config:

const featureFlagsConfig = selectConfig(ConfigModule, FeatureFlagsConfig);

@Module({})
export class CarsModule {
  static forAsync(): DynamicModule {
    const controllers = []
    const providers = []
    const exports = []
    if (featureFlagsConfig.cars) {
      controllers.push(...)
      exports.push(...)
      providers.push(...)
    }
    return {
      module: CarsModule,
      controllers,
      providers,
      exports,
    };
  }
}

Nikaple
  • 121
  • 6