graphql - 枚举 GraphQL 查询中的所有字段

标签 graphql apollo graphql-js apollo-server graphql-tools

给定 Apollo Server 的 GraphQL 架构和解析器和 GraphQL 查询,有没有办法在解析器函数中创建所有请求字段(在对象或映射中)的集合?

对于简单的查询,可以轻松地从解析器的 info 参数重新创建此集合。

给定一个架构:

type User {
  id: Int!
  username: String!
  roles: [Role!]!
}

type Role {
  id: Int!
  name: String!
  description: String
}

schema {
  query: Query
}

type Query {
  getUser(id: Int!): User!
}

和解析器:

Query: {
  getUser: (root, args, context, info) => {
    console.log(infoParser(info))

    return db.Users.findOne({ id: args.id })
  }
}

使用一个简单的递归 infoParser 函数,如下所示:

function infoParser (info) {
  const fields = {}

  info.fieldNodes.forEach(node => {
    parseSelectionSet(node.selectionSet.selections, fields)
  })

  return fields
}

function parseSelectionSet (selections, fields) {
  selections.forEach(selection => {
    const name = selection.name.value

    fields[name] = selection.selectionSet
      ? parseSelectionSet(selection.selectionSet.selections, {})
      : true
  })

  return fields
}

此日志中出现以下查询结果:

{
  getUser(id: 1) {
    id
    username
    roles {
      name
    }
  }
}

=> { id: true, username: true, roles: { name: true } }

事情很快就会变得非常丑陋,例如当您在查询中使用片段时:

fragment UserInfo on User {
  id
  username
  roles {
    name
  }
}

{
  getUser(id: 1) {
    ...UserInfo
    username
    roles {
      description
    }
  }
}

GraphQL 引擎在执行时正确忽略重复、(深度)合并等查询字段,但它没有反射(reflect)在 info 参数中。当您添加unions时和 inline fragments它只会变得更加毛茸茸。

考虑到 GraphQL 的高级查询功能,有没有办法构建查询中请求的所有字段的集合?

可以找到有关 info 参数的信息 on the Apollo docs site并在 graphql-js Github repo .

最佳答案

我知道已经有一段时间了,但如果有人最终来到这里,有一个名为 graphql-list-fields 的 npm 包通过 Jake Pusareti就是这样做的。它处理片段并跳过和包含指令。 您还可以查看代码here

关于graphql - 枚举 GraphQL 查询中的所有字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49184614/

相关文章:

javascript - GraphQl 中的注册身份验证不起作用 : Error:- signupUser: null

wordpress - 使用 WpGraphQL 显示草稿和待处理的帖子

javascript - 整数/十进制用户输入 : how to serialize/store the value

javascript - Graphql 需要外部模块与 GraphQLObjectType 内部模块

graphql - Hasura 查询的工作方式类似于 SQL 内连接

node.js - 使用 GraphQL NestJS 上传

javascript - 渲染后响应滚动到元素

node.js - 使用 Mongoose、node 和 graphql 防止控制台错误

graphql - 如何在graphql中为输入参数添加默认值

graphql - GraphQL 查询中的多项查找