Nestjs Custom configService for Applications in Nx Monorepo

Viewed 281

Im trying to create a custom configuration service for each of the nestjs applications within my nx monorepo. So far, this is the solution that I have come up with.

Each custom config service will inject the default nest configService, pass the nestjs configService a generic to indicate the list of configurations for that application. and wrap the retrieval of each configuration variable in a getter method. An example of such a service will look like this:

@Injectable()
export class AppConfigService {
  constructor(private readonly configService: ConfigService<envVars>) {}

  get nodeEnv(): Environment | undefined {
    return this.configService.get('NODE_ENV');
  }
}

The main config module for each application will be set as a global module and will use an alias provider so libraries that are used in multiple applications can access the config service by the same name regardless of the application that is using them:

const RootAppConfigModule = ConfigModule.forRoot({
  isGlobal: true,
  validate,
  envFilePath: './.env',
});

@Module({
  imports: [RootAppConfigModule],
  providers: [
    AppConfigService,
    {
      provide: 'AppConfigService',
      useClass: AppConfigService,
    },
  ],
})

Each service that requires the configService will then inject the config service token. The type of the value being injected will be a custom interface describing the configurations that are required in that service. The class’s constructor will also assert that the configurations exist on the injected configService:

@Injectable()
export class sessionThatUsesConfig {
  constructor(
    @Inject('AppConfigService') configService: configurations,
  ) {
    assert(configService.confgValue);
  }
  
  somethingThatNeedsAConfig() {
    console.log(this.configService.configVal)
  }
}

The main issue I am running into is that the injected appConfigService value on the is not recognized by the service injecting it. Has anyone done something like this before and if so, is there another way to go about this?

0 Answers
Related