About: webdev @ Autodesk |
Someone used to call me "Learn more", and I'm spending forever to live up to it. You'll find me dabbling in random stuff 👨💻 or missing a wide open shot in 🏀
Location:
Montreal
Joined:
Dec 12, 2018
Show off Github repos in your Gatsby site using Github GraphQL API
Publish Date: Jul 23 '20
58 5
Want to show off your Github repositories in your Gatsby site? 👨💼👩💼
Preview:
Even if you don't know GraphQL, this guide shows you just enough GraphQL to get you started learning it and using it. 🤓
We'll use Github GraphQL API v4 to get all the repositories from your Github account and display it in your Gatsby site! 📊
Let's get into it! 🏃♀️🏃♂️
GraphQL
Intro to GraphQL
A GraphQL API allows us to more efficiently create and consume APIs.
For example, we might fetch something like this using REST:
GET /api/:name/projects
GET /api/:name/projects/:project_id
GET /api/:name/projects/:project_id/description
GET /api/:name/projects/:project_id/name
GET /api/:name/projects/:project_id/watchers
GET /api/:name/projects/:project_id/watchers/:watcher_id
GET /api/:name/projects/:project_id/watchers/:watcher_id/name
In GraphQL, we don't have to "overfetch" and just get all data we need all at once from one endpoint:
query {
user(name: "myname") {
projects {
name
description
watchers {
name
}
}
}
}
That's just the tip of the iceberg for GraphQL. 🏔 ❄
For a more detailed guide to GraphQL:
They even provided a GraphiQL instance named "Gituhb GraphQL API explorer", which is basically an interactive "sandbox" for testing out queries on live Github data. 🧪
This is similar to the GraphiQL you can access locally on your Gatsby site, normally on http://localhost:8000/___graphql, but with the context of your Github account
...which gets your Github login, name, and names of your first 10 repositories.
The node here represent each of the repositories found, which we can get the fields name and description from.
The nice thing with GraphiQL is that it gives you auto-complete. The docs on the upper-right corner are also super useful.
The openGraphImageUrl contains your repo's Social Media Preview, which shows when you post your Github repo on Facebook, Twitter, blog, etc. This defaults to your Github profile photo, but it can be customized on the repo settings. Max 1MB for the photo. Photo by Christian Wiediger on Unsplash
Install and configure Gatsby Plugin for pulling data from Github GraphQL API
$ yarn add gatsby-source-github-api
Configure plugin in gatsby-config.js with the query
// gatsby-config.js// init. environment variablesconstdotenv=require('dotenv');dotenv.config();const{githubApiQuery}=require('./github-api')...plugins:[...{resolve:`gatsby-source-github-api`,options:{url:"https://api.github.com/graphql",// default Github GraphQL v4 API endpoint// token: required by the GitHub APItoken:process.env.GITHUB_PERSONAL_ACCESS_TOKEN,// GraphQLquery: defaults to a search querygraphQLQuery:githubApiQuery,// variables: defaults to variables needed for a search queryvariables:{github_login:process.env.GITHUB_LOGIN}}}...
Import the query from the module we created before
Configure the plugin so it can connect to Github GraphQL API successfully
Import Github credentials from .env: GITHUB_PERSONAL_ACCESS_TOKEN and GITHUB_LOGIN
Supply github_login variable here, so the $github_login variable in the query will have the value
Start it up! 👩🚀👨🚀
$ gatsby develop
Now that our data is available from the backend, let's use this on the frontend/UI side!
The nice thing is that it can appear anywhere in the component tree (vs page query that has to be top-level page component)
The nicer thing with the hooks version useStaticQuery is that you don't need Render Props to use it. Just run it and use the data result!
🔖 Github data only gets pulled once during build, since it's a Static Query after all. Meaning, it won't get latest updates from your Github, until site is rebuilt.
// pages/projects.js...import{useStaticQuery}from"gatsby"...exportdefaultfunctionProjects(){constdata=useStaticQuery(graphql`
query MyQuery {
allGithubData {
nodes {
data {
user {
repositories {
nodes {
description
forkCount
id
name
openGraphImageUrl
updatedAt(fromNow: true)
url
primaryLanguage {
name
}
languages {
nodes {
name
}
}
readme {
text
}
stargazers {
totalCount
}
}
}
}
}
}
}
}
`)constrepos=data.allGithubData.nodes[0].data.user.repositories.nodesconsole.log(repos)return (<div><h1>Projects</h1>
<h2>GithubRepos</h2>
<ul>{repos.map(repo=><likey={repo.id}>{repo.name}:{repo.description}</li>
)}</ul>
</div>
);
Note that our query pretty much reflects the query we passed to the plugin. The difference is that Gatsby gives us a bit more customizations for our frontend code.
For example, for the updatedAt field, we can upgrade from a boring timestamp "2020-07-16T02:06:57Z" to something like "updated 1 hour ago" with the use of updatedAt(fromNow: true) 🙂
From your Netlify dashboard, create new site and follow steps to create one from a Github repo
The nice thing is that you can specify the environment variables before deploy. 🤩
Remember that we can't commit .env to remote since that would expose our secrets to the cloud. 🤔 So we have to configure the env. variable directly on our cloud provider, which is Netlify in this case
Thanks, helpfull