DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Cover image for Github's GraphQl API with react-query and NextJs
Dennis kinuthia
Dennis kinuthia

Posted on

Github's GraphQl API with react-query and NextJs

working with Github's Graphql api

After working with the github rest api and experiencing some of it's limitations it's time to pick things up a bit and dive into their Graphql api

as Usual first things first we set up a testing environment and github provides their own explorer which will setup the authentication headers for you under the hood , but if you prefer to use another gql explorer , just set it up like below
Replace ghp_LBgN6pCeWsHcxeoJpR4ZTwUj with your personal access token

Image description

I have another article i made about react-query tips and tricks which might help explain that part . because i want to focus on the actual GraphQl queries in this one i'll mostly highlight the queries i used in the project and not go into details about the react part

final project live preview

let go

before we start we'll define a graphql Fragment that defines a User, this will come in handy because we'll be using it when querying the viewer ,user, follower , and following for uniformity so that if we need to add or remove a field we just do it once in the fragment and all the items defined by it change along with it.

import gql from "graphql-tag";

/// user fragments
export const OneUserFrag = gql`
  fragment OneUser on User {
    id
    name
    login
    email
    bio
    avatarUrl
    company
    twitterUsername
    createdAt
    isFollowingViewer
    viewerIsFollowing
    isViewer
    location
    url
    followers(first: 1) {
      totalCount
      nodes {
        id
      }
    }
    following(first: 1) {
      totalCount
      nodes {
        id
      }
    }

  repositories(first:1){
   totalCount
    nodes{
      id
    }
    }
  }
`;
Enter fullscreen mode Exit fullscreen mode

If you remember the REST api was lacking a few fields in the equivalent query isFollowingViewer ,
viewerIsFollowing ,
isViewer

which will help us avoid having to run other sub queries to check the follow status on every follower/following item

viewer

This query returns the currently logged in User , and I am using the personal access token to authenticate users since it's the simplest to implement.

//get currently logged in user
export const GETVIEWER = gql`
  query getViewer {
    viewer {
      ...OneUser
    }
  }
  ${OneUserFrag}
`;
Enter fullscreen mode Exit fullscreen mode

you'll notice that We're only fetching one follower , following , repository

      following(first: 1) {
        totalCount
        nodes {
          id
        }
      }
Enter fullscreen mode Exit fullscreen mode

and that's because we're only interested in the totalCount field at this point in order to diply it like this with all the counts

Image description

paginated fields

This is also because those three field require pagination and take the first ,last , after and before parameters

last and first is number of nodes and from which portion you want them from start of end and before and after are cursors , the api doe's generate cursors for us and can be accessed inside the page info field that's available in every paginated field

export const getUserWithFollowers = gql`
  query getUserFollowers($login: String!, $first: Int, $after: String) {
    user(login: $login) {
     followers(first: $first, after: $after) {
        pageInfo {
          endCursor
          hasNextPage
          hasPreviousPage
          startCursor
        }
        totalCount
        edges {
          node {
      ...OneUser
          }
        }
      }
    }
  }
   ${OneUserFrag}
`;
Enter fullscreen mode Exit fullscreen mode

in this example to fetch the next values , we'll pass in the endCursor into the after field on the next query

also note the GraphQl types

$login: String!, $first: Int, $after: String
Enter fullscreen mode Exit fullscreen mode

where String! is required and cannot be null , but String can be null , which is why the in initial query you can pass in after as null

This is also an example of graphql variables , where

  query getUserFollowers($login: String!, $first: Int, $after: String) {}
Enter fullscreen mode Exit fullscreen mode

wiltake in the variables login ,first and after
and pass them into the query

user(login: $login) {
followers(first: $first, after: $after) {
Enter fullscreen mode Exit fullscreen mode

and with queries with no variables you'll just write

   query getViewer {
    viewer {}
    }
Enter fullscreen mode Exit fullscreen mode

i've found it easier to avoid stuffing multiple paginated fields into one query and just break them of into smaller queries to be run by their own component which instead of a giant query to be rendered in one component

for example , once the viewer has been fetched the smaller components nested in the main component will have their own queries
one for repositories another for followers and following
they will be optionally rendered in a tab like way where by default it'll load the repository tab and the others will be shown if the user explicitly clicks on them which is when they'll run their sub query

User

similar to the viewer query but this will take one login (username) as a parameter and return the OneUserFragMent , useful when you want to navigate to another User obtained either from the follower list or Search results

export const GETONEUSER = gql`
  query getUser($login: String!) {
    user(login: $login) {
      ...OneUser
      }
   }
   ${OneUserFrag}
Enter fullscreen mode Exit fullscreen mode

Search

we'll also want the ability to search for random github user's by their username or password

export const USERSEARCH = gql `

query userSearch($query:String!,$first:Int,$type:SearchType!){
  search(query:$query,first:$first,type:$type){
    repositoryCount
    discussionCount
    userCount
    codeCount
    issueCount
    wikiCount

  edges{
    node{
  ... on User {
    login
    name
    email
    avatarUrl
    url
    }
  }
  }
 }
}

`
Enter fullscreen mode Exit fullscreen mode

the syntax below is better explained here but i short it lets us access items of a specific fragment since this query can return fragments of different types User , Repository , Code, Issue....

 ... on User {
Enter fullscreen mode Exit fullscreen mode

which allows you to write highly customizable queries like this

query userSearch($query:String!,$first:Int,$type:SearchType!){
  search(query:$query,first:$first,type:$type){
    repositoryCount
    discussionCount
    userCount
    codeCount
    issueCount
    wikiCount

  edges{
    node{
  ... on User {
    login
    name
    email
    avatarUrl
    url
    }
     ... on Repository{
      name
      url
      }
      ... on  Issue{
        id
        body
      }
  }
  }
 }
}
Enter fullscreen mode Exit fullscreen mode

follower

the follower query is basically this query

//get currently logged in user
export const GETVIEWER = gql`
  query getViewer {
    viewer {
      ...OneUser
    }
  }
  ${OneUserFrag}
`;
Enter fullscreen mode Exit fullscreen mode
export const GETONEUSER = gql`
  query getUser($login: String!) {
    user(login: $login) {
      ...OneUser
      }
   }
   ${OneUserFrag}
Enter fullscreen mode Exit fullscreen mode

but with the OneUser fragment being requested inside the the follower field

export const getUserWithFollowers = gql`
  query getUserFollowers($login: String!, $first: Int, $after: String) {
    user(login: $login) {
     followers(first: $first, after: $after) {
        pageInfo {
          endCursor
          hasNextPage
          hasPreviousPage
          startCursor
        }
        totalCount
        edges {
          node {
      ...OneUser
          }
        }
      }
    }
  }
   ${OneUserFrag}
`;
Enter fullscreen mode Exit fullscreen mode

the following field is also very similar

export const getUserWithFollowing = gql`
  query getUserFollowing($login: String!, $first: Int, $after: String) {
    user(login: $login) {
    following(first: $first, after: $after) {
        pageInfo {
          endCursor
          hasNextPage
          hasPreviousPage
          startCursor
        }
        totalCount
        edges {
          node {
       ...OneUser
          }
        }
      }
    }
  }
  ${OneUserFrag}
`;
Enter fullscreen mode Exit fullscreen mode

Repository

this field has a lot on it and it'll be all about what you want to display in your app
in my case i wanted to display something like this

Image description

I used ben awad's profile because his repositories actually have stars ,forks and multiple languages which is the brief info i want to see at a glance before i decide to click on it and see more

to achieve this i used this query

export const REPOS = gql`
         query getRepos($name: String!, $first: Int, $after: String) {
           user(login: $name) {
             login
             repositories(
               after: $after
               first: $first
               orderBy: { field: PUSHED_AT, direction: DESC }
             ) {
               edges {
                 node {
                   id,
                   name,
                   description,
                   pushedAt,
                   diskUsage,
                   url,
                   visibility,
                   forkCount,
                   stargazers(first: $first) {
                   totalCount
                   },
                   refs(
                     refPrefix: "refs/heads/"
                     orderBy: { direction: DESC, field: TAG_COMMIT_DATE }
                     first: 2
                   ) {
                     edges {
                       node {
                         name
                         id
                         target {
                           ... on Commit {
                             history(first: 1) {
                               edges {
                                 node {
                                   committedDate
                                   author {
                                     name
                                   }
                                   message
                                 }
                               }
                             }
                           }
                         }
                       }
                     }
                   }

                   languages(first: $first) {
                     edges {
                       node {
                         id
                         color
                         name
                       }
                     }
                   }
                 }
                 cursor
               }
               totalCount
               pageInfo {
                 startCursor
                 endCursor
                 hasNextPage
                 hasPreviousPage
               }
             }
           }
         }
       `;

Enter fullscreen mode Exit fullscreen mode

which is one moderately chonky query but returns everything i need in one query,

     refs(
                     refPrefix: "refs/heads/"
                     orderBy: { direction: DESC, field: TAG_COMMIT_DATE }
                     first: 2
                   ) {
                     edges {
                       node {
                         name
                         id
                         target {
                           ... on Commit {
                             history(first: 1) {
                               edges {
                                 node {
                                   committedDate
                                   author {
                                     name
                                   }
                                   message
                                 }
                               }
                             }
                           }
                         }
                       }
                     }
                   }
Enter fullscreen mode Exit fullscreen mode

in this bit am requesting for the 2 most recent commits and the branch on which it was made , the fact that this is possible in one query blows my mind which is another reason i really like graphql

but to top it all off am planning to implement a bigger query which i abandoned after realising it would be a pagination nightmare and would be better off being split up into smaller queries and each query being assigned it's child component which an be optionally rendered on user request but here it is anyway

const FULLREPO = gql`
# github graphql query to get more details  
  query getRepoDetails(
    $repoowner: String!,
    $reponame: String!,
    $first: Int,
    $after: String,
  ) {
    repository(owner: $repoowner, name: $reponame) {
    nameWithOwner,

      # get the repo collaborators

      collaborators(first: $first, after: $after) {
        edges {
          node {
            avatarUrl,
            email,
            name,
            bio,
            company
          },
        },
        pageInfo {
          endCursor,
          hasNextPage,
          hasPreviousPage,
          startCursor
        },
        totalCount
      }
      # end of collaborators

      # gets the repo vulnerabilities

      vulnerabilityAlerts(first: $first, after: $after) {
        edges {
          node {
            createdAt,
            securityAdvisory {
              classification,
              description,
              vulnerabilities(first: $first, after: $after) {
                edges {
                  node {
                    severity,
                    package {
                      name,
                      ecosystem
                    }
                  }
                },
                pageInfo {
                  endCursor
                  hasNextPage
                  hasPreviousPage
                  startCursor
                },
                totalCount
              }
            }
          }
        }
      },
      #   end of vulnerabilities block

      #refs: get branches and all the recent commits to it

      refs(
        refPrefix: "refs/heads/"
        orderBy: { direction: DESC, field: TAG_COMMIT_DATE }
        first: $first
        after: $after
      ) {
        edges {
          node {
            name
            id
            target {
              ... on Commit {
                history(first: $first, after: $after) {
                  edges {
                    node {
                      committedDate,
                      author {
                        name,
                        email
                      },
                      message,
                      url,
                      pushedDate,
                      authoredDate,
                      committedDate
                    }
                  }
                }
              }
            }
          }
        },
        pageInfo {
          endCursor,
          hasNextPage,
          hasPreviousPage,
          startCursor,
        },
        totalCount
        nodes {
          associatedPullRequests(first: $first, after: $after) {
            pageInfo {
              endCursor,
              hasNextPage,
              hasPreviousPage,
              startCursor,
            },
            totalCount
          }
        }
      }

      # end of refs block
      # languages
      languages(first: $first, after: $after) {
        edges {
          node {
            id,
            color,
            name
          }
        },
        pageInfo {
          endCursor,
          hasNextPage,
          hasPreviousPage,
          startCursor
        },
        totalCount
      }

      # end of languages block
      forkCount
      #fork block
      forks(first: $first, after: $after) {
        edges {
          node {
            createdAt,
            nameWithOwner,
            description,
            url,
            owner {
              login,
              url
            },
            parent {
              url,
              owner {
                login,
                url
              }
            }
          }
        }
        pageInfo {
          endCursor,
          hasNextPage,
          hasPreviousPage,
          startCursor,
        },
        totalCount
      }
      # end of fork block

      # star block
      stargazers(first: $first, after: $after) {
        edges {
          node {
            login,
            url
          }
        }
        pageInfo {
          endCursor,
          hasNextPage,
          hasPreviousPage,
          startCursor
        }
        totalCount
      }
      #end of star block
    }
  }
`;

Enter fullscreen mode Exit fullscreen mode

the query works fine , but only if you don't paginate because then you'll have to add more after variable for every paginated field and also handle the react-query / your gql client of choice

btw , check out example usage of react-query with graphql

final project live preview
next js usage
react-query tips and tricks
github rest api

Top comments (0)

Image description

Join the One Year Club

You can earn this badge by being a registered member of the DEV Community for at least one year. Create an account and get started today.