Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nestjs context.swithToHttp().getRequest() returns undefined

Tags:

graphql

nestjs

I want to create RolesGuard for Graphql

I create Roles decorator like following

export const Roles = (...roles: string[]) => SetMetadata('roles', roles);

And I create GqlAuthGuard and RolesGuard like following

gql-gurad.ts

@Injectable()
export class GqlAuthGuard extends AuthGuard('jwt') {
    getRequest(context: ExecutionContext){
        const ctx = GqlExecutionContext.create(context);
        return ctx.getContext().req;
    }
}

role-guard.ts

@Injectable()
export class RolesGuard implements CanActivate {
constructor(private readonly reflector: Reflector) {}

    canActivate(context: ExecutionContext): boolean {
        const roles = this.reflector.get<string[]>('roles', context.getHandler());
        if (!roles) {
            return true;
        }
        const request = context.switchToHttp().getRequest();
        const user = request.user;

        ...
    }
}

but line const request = context.switchToHttp().getRequest(); returns undefined.

and i'm using two guards like following

@AuthGuard(GqlAuthGuard, RolesGuard)
@Mutation(...)

What did I miss??

like image 394
fuzes Avatar asked Oct 22 '19 05:10

fuzes


1 Answers

I solved it myself.

const request = context.switchToHttp().getRequest();
const user = request.user;

to

const ctx = GqlExecutionContext.create(context);
const user = ctx.getContext().req.user;

i found it from nestjs discord channel.

https://discordapp.com/channels/520622812742811698/520649487924985885

like image 125
fuzes Avatar answered Oct 20 '22 00:10

fuzes