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

对于简单查询,可以从解析器的 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引擎正确地忽略了重复,(深度)合并等执行时查询的字段,但它没有反映在 info 参数中 . 当你添加unionsinline fragments时,它变得更加毛茸茸 .

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

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