Implement Github Graphs with D3.js (Part One)- 6 mins
As most Github user might notice, there is a graph page for each repository, which includes some charts to represents your coding data.
How about using d3.js wrapping with Github API to implement these charts?
Well, it all starts with reading the official document. By and large, if we want to represent more than just public data, it is necessary to be authenticated.
Although it is possible to authenticate by using username and password, it is rarely used in reality, whereas OAuth authentication is commonly used nowadays.
So basically OAuth2 is a protocol that allows external apps request authorization to private details in your Github account without getting your password. All application should be registered before getting started.
Before diving into specific codes, we need to understand what’s under the hood of the OAuth2 authentication process. In short, we send a request to
redirect_uri, after user accept this request, Github will redirect to the url with a
code parameter. This
code parameter will be used with
client_secret (which is in your application details) to exchange for an
access_token. Once you have the access_token, you can make request on the user’s behalf, namely, get these available user data.
The authentication is not very complicated, but in this case, we won’t be spending too much time on this since what we want is data.
I used Simple OAuth2:
As mentioned in the official document, there are many third party wrapper libraries for Github API, I used node-github.
Once you have the access token, calling api with
node-github is fairly easy, for example, to get a user’s repositories:
Use Express for Route and API
As for the web frame, I used
HandleBars as the view engine.
$ npm init
$ npm install express --save
--save to add as an dependencies in package.json.
It is feasible to use Express Generator to automatically generate the express frame, but for the sake of keeping things minimal viable, let’s create things manually.
Aside from regular things such as favicons, cookies etc, let’s keep this file simple:
So we’ll be updating the routes/index.js for apis.
For page rendering:
By far, we should be able to call an api and get response data, next we’ll try to imitate the Github repo graphs with d3.js. (part of the source code is here)