'nestjs graphql global guard

I'm trying to implement a global guard so that by default all requests that receive MUTATIONS from graphql need the token in their headers.

The latter works perfectly with the following code:

graphql-context-get-token.guard.ts


    import { ExecutionContext, Injectable } from '@nestjs/common';
    import { GqlExecutionContext } from '@nestjs/graphql';
    import { AuthGuard } from '@nestjs/passport';
    
    @Injectable()
    export class graphqlContextGetToken extends AuthGuard('jwt') {
      getRequest (context: ExecutionContext){
        const ctx = GqlExecutionContext.create(context);    
        return ctx.getContext().req;
      }
    }

app.module.ts


    @Module({
      imports: [    
        ConfigModule.forRoot({
          isGlobal: true
        }),
        TypeOrmModule. forRoot({
          type: 'postgres',
          host: 'localhost',
          port: 5432,
          username: 'postgres',
          password: '123456789',
          database: 'admin-emperator',
          entities: ['dist/**/*.entity{.ts,.js}'],
          synchronize: true,
        }),
        GraphQLModule.forRoot<ApolloDriverConfig>({
          driver: ApolloDriver,
          autoSchemaFile: join(process.cwd(), 'src/qraphql-schema.gql'),
        }),
        UsersModule, 
        AuthModule, 
        EmployeeModule,
      ],
      controllers: [],
      providers: [
        {
          provide: APP_GUARD,
          useClass: graphqlContextGetToken
        },
      ],
    })
    export class AppModule {}

my problem is that i need to create a decorator that when entering a flag by metadata allows the route that the decorator has, for example @Ispublic() not to be taken into account by the guard

user.resolver.ts


     /* DECORATOR HERE */
     @Query(()=>[UserEntity], {name: 'getAllUsers'})
        async findAll(@Context() context): Promise<UserEntity[]> {
            return this.userService.findAll();
        }

Before using graphql I used this decorator that fulfilled the task:

public.decorator.ts


    import { SetMetadata } from '@nestjs/common';
    export const IsPublic = () => SetMetadata('isPublic', true);

and my guard had the following logic:


    @Injectable()
    export class AccessTokenGuard extends AuthGuard('jwt') {
      constructor(private reflector: Reflector) {
        super();
      }
    
      canActivate(context: ExecutionContext) {
        const isPublic = this.reflector.getAllAndOverride('isPublic', [
          context.getHandler(),
          context.getClass(),
        ]);
        
        return isPublic ? true : super.canActivate(context);
      }
    }

but I have not managed to achieve the same result using graphql.

Thanks in advance.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source