4
votes

So I followed the guide on how to create a configuration for my Nest app

https://docs.nestjs.com/techniques/configuration

and due to the fact I have many configuration parts I wanted to split the parts into multiple configuration services. So my app.module.ts imports a custom config module

@Module({
  imports: [CustomConfigModule]
})
export class AppModule {}

This custom config module (config.module.ts) bundles all the config services and loads the Nest config module

@Module({
  imports: [ConfigModule.forRoot()],
  providers: [ServerConfigService],
  exports: [ServerConfigService],
})
export class CustomConfigModule {}

Lastly I have a simple config service server.config.service.ts which returns the port the application is running on

@Injectable()
export class ServerConfigService {
  constructor(private readonly configService: ConfigService) {}

  public get port(): number {
    return this.configService.get<number>('SERVER_PORT');
  }
}

I would like to validate those services on application startup. The docs explain how to setup a validationschema for the configuration module

https://docs.nestjs.com/techniques/configuration#schema-validation

How can I use that for my service validation when using a custom config module? Do I have to call joi in each service constructor and validate the properties there?

Thanks in advance

1

1 Answers

2
votes

I believe in your ConfigModule.forRoot() you can set the validation schema and tell Nest to run the validations on start up instead of having to add it to each custom config service. The docs show something like:

@Module({
  imports: [
    ConfigModule.forRoot({
      validationSchema: Joi.object({
        NODE_ENV: Joi.string()
          .valid('development', 'production', 'test', 'provision')
          .default('development'),
        PORT: Joi.number().default(3000),
      }),
      validationOptions: {
        allowUnknown: false,
        abortEarly: true,
      },
    }),
  ],
})
export class AppModule {}

Which would run validations on NODE_ENV and PORT. You could of course extend it out to more validations overall. And then you could just have one ConfigModule that has smaller config services that split each segment up so all validations are run on startup and only what you need is available in each module's context.