繁体   English   中英

如何在GraphQL和Nestjs执行上下文中访问父查询arguments

[英]How to access parent query arguments in GraphQL and Nestjs execution context

假设我们有一家书店和一个作者实体,为了向作者显示他们的收入统计数据,我们想检查经过身份验证的用户是否确实是作者本人。 所以我们有:

  @UseGuards(GqlAuthGuard)
  @ResolveField(() => [Eearning], { name: 'earnings' })
  async getEarnings(
    @Parent() author: Author,
    @GqlUser() user: User,
  ) {
    if (user.id !== author.id)
      throw new UnauthorizedException(
        'Each author can only view their own data',
      );
    // rest of the function implementation
  }

我们可以这样查询:

query {
  author(id: "2bd79-6d7f-76a332b06b") {
    earnings {
      sells
    }
  }
}

现在假设我们想要使用自定义 Guard 而不是 if 语句。 像下面这样的东西:

@Injectable()
export class AutherGuard implements CanActivate {
  canActivate(context: ExecutionContext): boolean {
    const ctx = GqlExecutionContext.create(context);
    // const artistId = ?
  }
}

AutherGuard用于getEarnings处理程序时,如何访问提供给author查询的id参数?

不确定是如何记录的,但是可以通过getRoot方法访问父 object:

const gqlContext = GqlExecutionContext.create(context);
const root = gqlContext.getRoot();
const authorId = root.id;

事实上,我们有一个 helper function,我们可以这样使用:

export function getArgs(context: ExecutionContext): any {
  if (context.getType<GqlContextType>() === "graphql") {
    const gqlContext = GqlExecutionContext.create(context);
    return { ...gqlContext.getArgs(), $parent: gqlContext.getRoot() };
  } else if (context.getType() === "http") {
    return context.switchToHttp().getRequest().params;
  }
}

...
const args = getArgs(context);
const authorId = _.get(args, "$parent.id");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM