Shahar Shmaram
Shahar Shmaram

Reputation: 243

Nest JS - Unable to inject service to middlewere

I have created an auth middlewere for checking each request, the middlewere is using server (only if data was not found in the req.connection). I'm trying to inject the service into my middlewere and I keep getting the same error "Nest can't resolve dependencies of the AuthenticationMiddleware (?). Please verify whether [0] argument is available in the current context."

AuthenticationModule:

@Module({
   imports: [ServerModule],
   controllers: [AuthenticationMiddleware],
})
export class AuthenticationModule {
}

AuthenticationMiddleware:

@Injectable()
export class AuthenticationMiddleware implements NestMiddleware {

constructor(private readonly service : UserService) {}

resolve(): (req, res, next) => void {
 return (req, res, next) => {
   if (req.connection.user)
    next();

  this.service.getUsersPermissions()     
  }
}

ServerModule:

@Module({
 components: [ServerService],
 controllers: [ServerController],
 exports: [ServerService]
})    
 export class ServerModule {}

ApplicationModule:

@Module({
  imports: [
    CompanyModule,
    ServerModule,
    AuthenticationModule
  ]
})

export class ApplicationModule implements NestModule{
  configure(consumer: MiddlewaresConsumer): void {
  consumer.apply(AuthenticationMiddleware).forRoutes(
      { path: '/**', method: RequestMethod.ALL }
   );
 }
}

Upvotes: 8

Views: 15036

Answers (1)

Caio Ferreira
Caio Ferreira

Reputation: 304

Your application can't resolve AuthMiddleware dependencies probably because you inject an UserService into it but the ServerModule that you import into your AuthenticationModulejust exports a ServerService. So, what should be made is:

@Injectable()
export class AuthenticationMiddleware implements NestMiddleware {

  constructor(private readonly service : ServerService) {}

  resolve(): (req, res, next) => void {
    return (req, res, next) => {
      if (req.connection.user)
        next();

    this.service.getUsersPermissions()     
  }
}

You can find more about the NestJS dependency container here.

Upvotes: 13

Related Questions