如何从已解析的 graphql 中删除不需要的节点?

How to remove unwanted node from a parsed graphql?

例如,如果我有这样的代码:

import gql from 'graphql-tag'

const getUserMeta = /* GraphQL */ `
  query GetUserMeta($owner: String!) {
    getUserMeta(owner: $owner) {
      familyName
      givenName
      workAddress
      facebookUrl
      owner
      createdAt
      updatedAt
      careers {
        items {
          id
          company
          companyUrl
          showCompany
          owner
          createdAt
          updatedAt
        }
        nextToken
      }
    }
  }
`;

const ast = gql(getUserMeta)


// for example if I want to remove the `showCompany` node
// I expect some method like this would work... but there is no such a method..
// ast.removeNodeByPath('GetUserMeta.careers.showCompany')

apolloClient.query(query:ast, variables: {limit: 100})

看这里:https://graphql.org/graphql-js/constructing-types/

graphql-js 库提供了操作 AST 的函数。

我建议使用该页面上记录的 visitor 函数。

这是一段代码,使用访问者添加一些东西(正是我的产品的一部分),它可以为您提供一个入门模型。

 let editedAst = visit(stage.graphQLDocument, {
  SelectionSet: {
    leave(node, key, parent, path, ancestors) {
      if (
        ancestors.length === 5 &&
        (ancestors[2] as OperationDefinitionNode).kind ===
          'OperationDefinition' &&
        (ancestors[3] as SelectionSetNode).kind === 'SelectionSet'
      ) {
        if (
          node.selections.find((s) => {
            return (s as FieldNode).name.value === CHUNK_ID;
          })
        ) {
          return undefined;
        }
        const fieldChunkId = {
          kind: 'Field',
          directives: [],
          name: { kind: 'Name', value: CHUNK_ID },
        };

        return {
          ...node,
          selections: [...node.selections, fieldChunkId],
        };
      }
    },
  },