Graphql 如何从'gql'对象获取查询的名称?

Graphql 如何从'gql'对象获取查询的名称?,graphql,apollo,graphql-tag,Graphql,Apollo,Graphql Tag,我使用来自的gql。 假设我有一个定义如下的gql对象: const QUERY_ACCOUNT_INFO = gql` query AccountInfo { viewer { lastname firstname email phone id } } ` 必须有办法从中获取AccountInfo。我怎么做 gql返回的是一个对象。GraphQL文档可以包含多个定义,但假设它只有一个定义,并且是一个操作,则可

我使用来自的
gql
。 假设我有一个定义如下的
gql
对象:

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

必须有办法从中获取
AccountInfo
。我怎么做

gql返回的是一个对象。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

如果您使用的是Apollo,那么还有显式的
getOperationName
,它似乎没有文档化,但在我的所有用例中都有效

import { getOperationName } from "@apollo/client/utilities";

export const AdminListItemsDocument = gql`
  query AdminListItems(
    $first: Int
    $after: String
    $before: String
    $last: Int
  ) {
    items(
      first: $first
      after: $after
      before: $before
      last: $last
    ) {
      nodes {
        id
        name
      }
      totalCount
      pageInfo {
        hasPreviousPage
        hasNextPage
        startCursor
        endCursor
      }
    }
  }
`;

getOperationName(AdminListBlockLanguagesDocument); // => "AdminListItems"

如果我使用getOperationAST,我会得到typescript错误:应为2个参数,但得到1个参数。如果我使用operation=doc.definition[0]。。。然后我得到类型脚本错误属性“name”在类型“DefinitionNode”上不存在