Github List Repositories Paginated with GraphQL

One of the Github GraphQL operations supporting pagination is searching/listing repositories. Below queries utilize query variables running in GitHub’s GraphQL Explorer.

{
  "query": "org:gliptak is:all",
  "pageSzie": 2,
  "after": ""
}

Below setup has 2 for pagination size for demonstration purposes, larger window to be used in real queries. The initial query:

query ListRepos($query: String!, $pageSize: Int!) {
  search(query: $query, type: REPOSITORY, first: $pageSize) {
    edges {
      node {
        ... on Repository {
          name
          defaultBranchRef {
            name
          }
        }
      }
    }
    pageInfo {
      startCursor
      endCursor
      hasNextPage
    }
  }
}

returns repo details and cursor values:

{
  "data": {
    "search": {
      "edges": [
        {
          "node": {
            "name": "JAllele",
            "defaultBranchRef": {
              "name": "master"
            }
          }
        },
        {
          "node": {
            "name": "aws-cdk-python",
            "defaultBranchRef": {
              "name": "master"
            }
          }
        }
      ],
      "pageInfo": {
        "startCursor": "Y3Vyc29yOjE=",
        "endCursor": "Y3Vyc29yOjI=",
        "hasNextPage": true
      }
    }
  }
}

Which can be used to form the next query:

query ListRepos($query: String!, $pageSize: Int!, $after: String!) {
  search(query: $query, type: REPOSITORY, after: $after, first: $pageSize) {
    edges {
      node {
        ... on Repository {
          name
          defaultBranchRef {
            name
          }
        }
      }
    }
    pageInfo {
      startCursor
      endCursor
      hasNextPage
    }
  }
}

Above will return similar JSON and to be called with next after cursor value while hasNextPage is true.

comments powered by Disqus

Related