【问题标题】:How to get the name of a query from a `gql` object?如何从“gql”对象中获取查询的名称?
【发布时间】:2020-02-08 18:02:44
【问题描述】:

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

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

一定有办法从中获取AccountInfo。我该怎么做?

【问题讨论】:

    标签: graphql apollo graphql-tag


    【解决方案1】:

    如果您使用的是 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"
    

    【讨论】:

      【解决方案2】:

      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
      

      【讨论】:

      • 如果我使用 getOperationAST,我会收到打字稿错误:Expected 2 arguments but got 1.
      • 如果我使用 operation = doc.definition[0] ... 方式然后我得到打字稿错误 Property 'name' does not exist on type 'DefinitionNode'
      • 附带问题:如何对片段做同样的事情?问题不同,但谷歌搜索把我带到了这里
      猜你喜欢
      • 1970-01-01
      • 2019-07-23
      • 2014-10-09
      • 2013-06-13
      • 2013-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-05
      相关资源
      最近更新 更多