【问题标题】:filtering out zero total from nested result in graphql query在graphql查询中从嵌套结果中过滤掉零总数
【发布时间】:2021-09-12 05:49:52
【问题描述】:

我有以下可以针对 github graphql API 运行的查询

query userRepositories($cursor: String, $q: String!, $githubId: String!) {
  search(query: $q, type: REPOSITORY, first: 100, after: $cursor) {
    repositoryCount
    pageInfo {
      endCursor
      startCursor
    }
    nodes {
      ... on Repository {
        id
        name
        description
        isArchived
        isPrivate
        nameWithOwner
        url
        defaultBranchRef {
          target {
            ... on Commit {
              history(first: 10, author: {id: $githubId}) {
                totalCount
              }
            }
          }
        }
      }
    }
  }
}

返回结果如下:

{
  "data": {
    "search": {
      "repositoryCount": 103,
      "pageInfo": {
        "endCursor": "Y3Vyc29yOjEwMA==",
        "startCursor": "Y3Vyc29yOjE="
      },
      "nodes": [
        {
          "id": "MDEwOlJlcG9zaXRvcnk2MTg1OTczOA==",
          "name": "microstates",
          "nameWithOwner": "thefrontside/microstates",
          "url": "https://github.com/thefrontside/microstates",
          "defaultBranchRef": {
            "target": {
              "history": {
                "totalCount": 0
              }
            }
          },        
         {
          "id": "MDEwOlJlcG9zaXRvcnkxNTU5MTUyODc=",
          "name": "effection",
          "nameWithOwner": "thefrontside/effection",
          "url": "https://github.com/thefrontside/effection",
          "defaultBranchRef": {
            "target": {
              "history": {
                "totalCount": 16
              }
            }
          }
        },

我只对 defaultBranchRef.target.history.totalCount 大于 0 的节点数组感兴趣。

所以我对 nodes 数组的元素 0 不感兴趣,但我对元素 1 感兴趣。

我可以在 graphql 中过滤,还是必须在查询之外的代码中过滤?

【问题讨论】:

    标签: graphql


    【解决方案1】:

    GraphQL 无法过滤数组,因此如果 API 支持基于 totalCount 的过滤器,您可以通过此过滤器,否则您必须在代码中进行过滤。在 JS 中很简单:

    const filtered = {
      ...data,
      search: {
        ...data.search,
        nodes: data.search.nodes.filter(node => node.defaultBranchRef.target.history.totalCount > 0),
      }
    };
    

    【讨论】:

      猜你喜欢
      • 2019-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-18
      相关资源
      最近更新 更多