0
votes

I am trying to add an auth guard to a GraphQL resolver but it doesn't seem to be working as expected.

I have a simple guard that should reject all requests:

@Injectable()
export class AuthGuard implements CanActivate {
  canActivate(context: ExecutionContext): boolean {
    return false;
  }
}

and have applied it in a resolver:

@Resolver()
export class RecipeResolver {
  
  @Query(() => [Recipe])
  @UseGuards(AuthGuard)
  public recipes(): Recipe[] {
    return this.recipeData;
  }
}

This does not work in the resolver and the canActivate is never fired. This does work in an HTTP Controller.

Changing @UseGuards(AuthGuard) to @UseGuards(new AuthGuard()) works but will not go through the dependency injection process which is not ideal.

What am I doing wrong?

Edit:

original app.module.ts:

@Module({
  imports: [
    GraphQLModule.forRoot({
      autoSchemaFile: 'shcema.gql',
      playground: true,
    }),
    RecipeResolver,
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}
1
From what you've shown, I don't see anything wrong. It looks fine to me - Jay McDoniel
@JayMcDoniel I added a link to a github repo that shows the issue I am running into - bsthedev
Why is your RecipeResolver in the AppModule's imports array? It should be in the providers - Jay McDoniel
@JayMcDoniel moving it from imports to providers fixed the issue. Thank you! - bsthedev

1 Answers

0
votes

From the code, the resolver was in the wrong location (in an imports array instead of providers) which meant Nest didn't set up the request lifecycle properly.