nestjs context.swithToHttp().getRequest()返回未定义 [英] nestjs context.swithToHttp().getRequest() returns undefined

查看:150
本文介绍了nestjs context.swithToHttp().getRequest()返回未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为Graphql创建RolesGuard

I want to create RolesGuard for Graphql

我创建如下的角色装饰器

I create Roles decorator like following

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

然后我像下面创建GqlAuthGuard和RolesGuard

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;

        ...
    }
}

但行 const request = context.switchToHttp().getRequest(); 返回未定义.

我正在使用两个如下的警卫队

and i'm using two guards like following

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

我想念什么?

推荐答案

我自己解决了.

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

to

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

我是从nestjs不和谐频道中找到的.

i found it from nestjs discord channel.

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

这篇关于nestjs context.swithToHttp().getRequest()返回未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆