gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 18:40:32 26 4
gpt4 key购买 nike

给定 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com