Nestjs | ConfigModule | Use (or inject) a service inside `validate` function

Viewed 608
import { validate } from './env.validation';

@Module({
  imports: [
    ConfigModule.forRoot({
      validate,
    }),
  ],
})
export class AppModule {}

How can I use some service from within validate function? For example a Logger service?
Can a service be injected into validate?

2 Answers

as you could see in it source code here there is no way to inject providers in this validate function because it is just a conventional callback that doesn't know about the Nest DI system.

Heading

In your case, I would build a class to implement ValidatorConstraintInterface, which is from class-validator. Then, you can use the answer from this issue to inject dependencies: https://github.com/nestjs/nest/issues/528

TL:DR use this on your bootstrap() and implement the ValidatorConstraintInterface, so you can inject dependencies:

useContainer(app.select(AppModule), {fallbackOnErrors: true});

Related