Conditionally disable controller endpoints and remove exports using value from configuration service using nestjs

Viewed 830

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,
    };
  }
}

1 Answers

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,
    };
  }
}

Related