gpt4 book ai didi

graphql - 如何从 `gql` 对象中获取查询的名称?

转载 作者:行者123 更新时间:2023-12-04 16:28:18 25 4
gpt4 key购买 nike

我用 gql来自 graphql-tag .
假设我有一个 gql对象定义如下:

const QUERY_ACCOUNT_INFO = gql`
query AccountInfo {
viewer {
lastname
firstname
email
phone
id
}
}
`

一定有办法拿到 AccountInfo从中。我该怎么做?

最佳答案

gql 返回了什么|是 DocumentNode目的。一个 GraphQL 文档可以包含多个定义,但假设它只有一个并且是一个操作,您可以这样做:

const operation = doc.definitions[0]
const operationName = operation && operation.name

如果我们允许可能有碎片,我们可能想要这样做:
const operation = doc.definitions.find((def) => def.kind === 'OperationDefinition')
const operationName = operation && operation.name

请记住,在同一文档中存在多个操作在技术上是可能的,但是如果您针对自己的代码运行此客户端,则该事实可能无关紧要。

核心库还提供了一个实用函数:
const { getOperationAST } = require('graphql')
const operation = getOperationAST(doc)
const operationName = operation && operation.name

关于graphql - 如何从 `gql` 对象中获取查询的名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58337364/

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