I’m using NestJS for my app and using the @UseGuards()
. I also created 2 guards for my controller like:
JwtAuthGuard:
import { AuthGuard } from '@nestjs/passport';
export class JwtAuthGuard extends AuthGuard('jwt') {}
ApiKeyGuard:
@Injectable()
export class ApiKeyGuard implements CanActivate {
constructor(private configService: ConfigService) {}
canActivate (context: ExecutionContext) {
const request = context.switchToHttp().getRequest();
const { apikey } = request.headers;
if (apikey === env.get('API_KEY')) return true;
else throw new UnauthorizedException();
}
}
This my Controller:
@Get('/:users')
@UseGuards(ApiKeyGuard)
getUser(): {
return this.userService.getUser();
}
and the services look like:
@Injectable()
export class UserService {
constructor(private dummyService:DummyService) {}
getUser() {
return this.dummyService.getUser();
}
Here is the module.ts
file:
@Module({
imports: [...],
controllers: [userController],
providers: [....],
exports: [UserService],
})
export class CouponModule {}
I also have another module named CouponModule
has CouponController
which is also used that @UseGuard()
and its services: the CouponService
is circular dependencies with the UserService
and also use the DummyService
as well
Problem:
All the API that has the @UseGuards(ApiKeyGuard)
in the controller are returning error when the app processing requests:
TypeError: Cannot read property 'getUser' of undefined
But when I use the @UseGuards(JwtAuthGuard)
for that API, the app worked normally and no error was thrown. Even when I removed the @UseGuards()
decorator, the error happened again.
I also tried to add that DummyServices
to the providers of the module.ts
file for both but it does not solve the problem.
I’ve done lots of searching and investigating and still can not found any the root cause or the solution for this.