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

Vla*_*tko 3 apollo graphql graphql-tag

我使用gql来自graphql-tag。假设我有一个这样gql定义的对象:

const QUERY_ACCOUNT_INFO = gql`
  query AccountInfo {
    viewer {
      lastname
      firstname
      email
      phone
      id
    }
  }
`
Run Code Online (Sandbox Code Playgroud)

必须有办法摆脱AccountInfo它。我该怎么做?

Mar*_*mer 13

如果您使用 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"
Run Code Online (Sandbox Code Playgroud)


Dan*_*den 5

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

const operation = doc.definitions[0]
const operationName = operation && operation.name
Run Code Online (Sandbox Code Playgroud)

如果我们允许可能有碎片,我们可能想要这样做:

const operation = doc.definitions.find((def) => def.kind === 'OperationDefinition')
const operationName = operation && operation.name
Run Code Online (Sandbox Code Playgroud)

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

核心库还提供了一个实用函数:

const { getOperationAST } = require('graphql')
const operation = getOperationAST(doc)
const operationName = operation && operation.name
Run Code Online (Sandbox Code Playgroud)

  • 如果我使用操作= doc.definition [0] ...方式然后我得到打字稿错误属性'名称'在类型'DefinitionNode'上不存在 (3认同)