Search code examples
typescriptnestjsnestjs-passport

NestJs reusing a guard that has uses multiple service gives "a Invalid guard passed to @UseGuards()" error


I'm trying to retrieve the current user in a guard to give him access or no. I have a guard that isn't doing anything for now


@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {
  constructor (
    private readonly studentService: StudentService,
    private readonly agencyService: AgencyService
  ) {
    super()
  }
}

When I add it to two controllers like that

@UseGuards(JwtAuthGuard /* CrudAbilitiesGuard */)
  @ApiBearerAuth('access-token')
  @ApiBody({ type: CreateStudentDto })
  @Post()
  async create (
    @Body() newStudentDto: CreateStudentDto
  ): Promise<StudentDocument> {
    const student = await this.service.create(newStudentDto)
    if (student == null) throw new InternalServerErrorException()
    return student
  }

it throws Error: Invalid guard passed to @UseGuards() decorator

if I only use the guard in one controller, it works fine, if I comment both the services in the constructor and use it in two controllers, it also works. Seems like nest a casual hidden circular dependency but i really can't get my head around it

Edit:

Same result with a Guard that extends CanActivate directly

@Injectable()
export class CrudAbilitiesGuard implements CanActivate {
  constructor (
    private readonly agencyService: AgencyService,
    private readonly studentService: StudentService,
    private readonly reflector: Reflector,
    private readonly caslAbilityFactory: CaslAbilityFactory
  ) {}
  async canActivate (context: ExecutionContext): Promise<boolean> {
    return true
  }
}

Solution

  • Alright, massive noob mistake. In an effort of not having 300+ files I had small modules in the same file (service + controller + schemas, etc) leading to of course billions of inter-dependency and circular issues of all kinds. Note to myself: Module means MODULE