Obvious_Grapefruit
Obvious_Grapefruit

Reputation: 880

How to consume a Service in Nest.js middleware

I need to use HttpService from @nestjs/axios in some middleware to verify captcha responses.

I have registered the middleware in app.module.ts like this:

@Module({
  // ...
  controllers: [AppController],
  providers: [AppService, HttpService] <---- added HttpService here
})

export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer
      .apply(CaptchaMiddleware)
      .forRoutes(
        { path: '/users', method: RequestMethod.POST }
      );
  }
}

This is what captcha.middleware.ts looks like:

@Injectable()
export class CaptchaMiddleware implements NestMiddleware {

    constructor(
        private readonly httpService: HttpService
    ) { }

    async use(req: Request, res: Response, next: NextFunction) {

        // ... code to verify captcha ...
      
    }
}

But I get this error:

 ERROR [ExceptionHandler] Nest can't resolve dependencies of the HttpService (?). Please make sure that the argument AXIOS_INSTANCE_TOKEN at index [0] is available in the AppModule context.

Potential solutions:
- If AXIOS_INSTANCE_TOKEN is a provider, is it part of the current AppModule?
- If AXIOS_INSTANCE_TOKEN is exported from a separate @Module, is that module imported within AppModule?
  @Module({
    imports: [ /* the Module containing AXIOS_INSTANCE_TOKEN */ ]
  })

What is the correct way to add HttpService as a dependency of CaptchaMiddleware?

Upvotes: 1

Views: 2902

Answers (1)

Jay McDoniel
Jay McDoniel

Reputation: 70171

You should be importing the HttpModule, not providing the HttpService. Just like it's described in the docs. When you provide a provider, Nest tries to make an instance of that provider, when you import the module, Nest will re-use the provider if it exists or create a new one with the module's provider definition.

Upvotes: 2

Related Questions