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

查看:244
本文介绍了如何知道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天全站免登陆