GraphQL

TIL – Github GraphQL Direct Lookup By ID

TIL – Github GraphQL Direct Lookup By ID

Being a version 3 user for a long time (Github REST), I find it hard to convert some of the common REST queries into GraphQL queries for Github. I was specifically looking at the REST API endpoint to list collaborators of a repository.

https://docs.github.com/en/rest/reference/repos#list-repository-collaborators

The path looks like this:

GET repos/{owner}/{repo}/collaborators

For the REST API to work, I need to know the repository owner and the repository name.

Converting this query into GraphQL looks like this.

query GetRepoCollaborators($owner: String!, $name: String!) {
  repository(name: $name, owner: $owner) {
    id
    collaborators(first: 10) {
      edges {
        node {
          id
          login
          name
          avatarUrl
        }
      }
    }
  }
}

The conversion is pretty straight forward. However, there is an issue with renamed repositories. Also, owners can also change their usernames. This will cause problems as it will break the API calls.

ID Lookup

In our application, we heavily rely on the object IDs which are called node_id in the version 3. We store them and use them as key. To convert our original GraphQL query to ID lookup, we will change our root from repository to node and use the global Node ID to lookup the object then use the connections to fetch the collaborators.

query GetRepoCollaborators($repoId: ID!String) {
  node(id: $repoId) {
    ... on Repository {
      id
      collaborators(first: 10) {
        edges {
          node {
            id
            login
            name
            avatarUrl
          }
        }
      }
    }
  }
}

Now we don’t event need to know the owner of the repo. As long as our integration app/user has access to the repository, it should be able to list the repo collaborators without issues.

That’s it!

Featured image by Andrea Piacquadio: https://www.pexels.com/photo/woman-draw-a-light-bulb-in-white-board-3758105/

No Comments

Leave a reply

Your email address will not be published. Required fields are marked *