2
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?

fmagno
  • 1,446
  • 12
  • 27

2 Answers2

1

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.

Micael Levi
  • 5,054
  • 2
  • 16
  • 27
  • I'm trying to use as much as possible the nestjs ConfigModule, its validation mechanisms and its services but to also be able to use other custom services across the board. Do you have a suggestion on how to approach this problem? – fmagno May 02 '21 at 17:28
  • It's still not clear to me how one can effectively use the ConfigModule and be able to, for example, log a message when something goes wrong during the validation call. – fmagno May 02 '21 at 17:44
  • that lib will thrown an error when the validation fails, and the app will not start. See https://github.com/nestjs/config/blob/2d3fc708eee8b38f7d27ec562011bbd3cc831e0e/tests/e2e/validate-function.spec.ts#L17 maybe you can use that error somehow to do what you want to, or build your own `ConfigModule` :/ – Micael Levi May 02 '21 at 18:31
1

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

  • How you pass the `validate` method, of your suggested new service, to the ConfigModule.forRoot({ validate })? – fmagno May 04 '21 at 09:49