如何知道 GraphQL 查询中请求了哪些字段? [英] How to know which fields were requested in a GraphQL query?

查看:15
本文介绍了如何知道 GraphQL 查询中请求了哪些字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个 GraphQL 查询,如下所示:

I have written a GraphQL query which like the one below:

{
  posts {
    author {
      comments
    }
    comments
  }
}

我想知道如何在 posts 解析器中获取有关请求的子字段的详细信息.

I want to know how can I get the details about the requested child fields inside the posts resolver.

我想这样做是为了避免解析器的嵌套调用.我正在使用 ApolloServer 的 DataSource API.

I want to do it to avoid nested calls of resolvers. I am using ApolloServer's DataSource API.

我可以更改 API 服务器以一次性获取所有数据.

I can change the API server to get all the data at once.

我正在使用 ApolloServer 2.0,也欢迎任何其他避免嵌套调用的方法.

I am using ApolloServer 2.0 and any other ways of avoiding nested calls are also welcome.

推荐答案

您需要解析作为第四个参数传递给解析器的 info 对象.这是对象的类型:

You'll need to parse the info object that's passed to the resolver as its fourth parameter. This is the type for the object:

type GraphQLResolveInfo = {
  fieldName: string,
  fieldNodes: Array<Field>,
  returnType: GraphQLOutputType,
  parentType: GraphQLCompositeType,
  schema: GraphQLSchema,
  fragments: { [fragmentName: string]: FragmentDefinition },
  rootValue: any,
  operation: OperationDefinition,
  variableValues: { [variableName: string]: any },
}

您可以自己遍历该领域的 AST,但最好使用现有的库.我推荐 graphql-parse-resolve-info.还有许多其他库,但 graphql-parse-resolve-info 是一个非常完整的解决方案,实际上由 postgraphile 在幕后使用.示例用法:

You could transverse the AST of the field yourself, but you're probably better off using an existing library. I'd recommend graphql-parse-resolve-info. There's a number of other libraries out there, but graphql-parse-resolve-info is a pretty complete solution and is actually used under the hood by postgraphile. Example usage:

posts: (parent, args, context, info) => {
  const parsedResolveInfo = parseResolveInfo(info)
  console.log(parsedResolveInfo)
}

这将沿着这些行记录一个对象:

This will log an object along these lines:

{
  alias: 'posts',
  name: 'posts',
  args: {},
  fieldsByTypeName: {
    Post: {
      author: {
        alias: 'author',
        name: 'author',
        args: {},
        fieldsByTypeName: ...
      }
      comments: {
        alias: 'comments',
        name: 'comments',
        args: {},
        fieldsByTypeName: ...
      }
    }
  }
}

您可以遍历生成的对象并相应地构建您的 SQL 查询(或一组 API 请求,或其他任何内容).

You can walk through the resulting object and construct your SQL query (or set of API requests, or whatever) accordingly.

这篇关于如何知道 GraphQL 查询中请求了哪些字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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