Home > front end >  How to properly inject a service into a guard
How to properly inject a service into a guard

Time:12-19

I am working on an API with nestjs and I have a problem with service injection in a guard. The following error occurs:

Error: Nest can't resolve dependencies of the AuthorizerGuard (?). Please make sure that the argument Object at index [0] is available in the PostsModule context.

I consulted several posts related to this topic but no solution works and I don’t understand what to do (I’m new to nestjs).

Currently my files:

authorizer.module.ts

@Module({
  providers: [AuthorizerService],
  exports: [AuthorizerService],
})
export class AuthorizerModule {}

authorizer.guard.ts

import {
  CanActivate,
  ExecutionContext,
  Inject,
  Injectable,
  Logger,
  UnauthorizedException,
} from '@nestjs/common';

@Injectable()
export class AuthorizerGuard implements CanActivate {
  constructor(private readonly AuthorizerService) {}
  async canActivate(context: ExecutionContext): Promise<boolean> {
    //my code
  }
}

posts.module.ts

@Module({
  imports: [AuthorizerModule],
  controllers: [PostsController],
  providers: [PostsService],
})
export class PostsModule {}

posts.controller.ts

@UseGuards(AuthorizerGuard)
export class PostsController {}

authorizer.service.ts

@Injectable()
export class AuthorizerService {
  prisma = new PrismaClient();

  async findUseridByEmail(email: string) {
    return await this.prisma.user.findUnique({
      where: {
        email,
      },
    });
  }
}

Thanks for your help:)

CodePudding user response:

More than likely this is related to how you import AuthorizerService in your AuthorizerGuard. If you use impot type instead of a regular import then the class AuthorizerService doesn't actually become the metadata that typescript emits and instead you are left with Object or {}. Because of this, Nest can't read the metadata of the constructor parameters for your AuthorizerGuard and throws an error.

  • Related