dagda1
dagda1

Reputation: 28920

filtering out zero total from nested result in graphql query

I have the following query that can be run against the 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
              }
            }
          }
        }
      }
    }
  }
}

It returns results like this:

{
  "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
              }
            }
          }
        },

I am only interested in the nodes array that has a defaultBranchRef.target.history.totalCount that is greater than 0.

So I am not interested in element 0 of the nodes array but I am of element 1.

Can I filter this in graphql or do I have to do that in code outside of the query?

Upvotes: 3

Views: 448

Answers (1)

Masih Jahangiri
Masih Jahangiri

Reputation: 10967

GraphQL can't filter an array so if the API support filter base on totalCount you can pass this filter otherwise you have to filter in your code. In JS it's very easy:

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

Upvotes: 1

Related Questions