Ads

 

How to use github API on a static webpage

For the new rainbrurpg homepage, I would like to dynamically add the github's repositories status, for example the last commits.

Dynamically retrieved commits from RainbruRPG's repository


With the gh3 library

The gh3 library is a client-side javascript wrapper for the github V3 API. To use it, you will need to insert 3 javascript files :
<script type="text/javascript" src="js/jquery-2.1.0.min.js"></script>
<script type="text/javascript" src="js/underscore-min.js"></script>
<script type="text/javascript" src="js//gh3.min.js"></script>

Then, you'll need to add an HTML code for  your commit log :
<div id="commits">

</div>

And now, we'll dynamically fetch repository informations using gh3 and add it to the page using jquery :

var rain = new Gh3.User("rainbru")

rain.fetch(function (err, resUser){

  if(err) {
    throw "can't fetch github user ..."
  }

var rpg = new Gh3.Repository("rainbrurpg.github.com", rain);

rpg.fetch(function (err, res){

  if(err) {
    throw "can't fetch github repository ..."
  }

console.log(rain, resUser);
// logs many informations but not the latest commits list
});

Since I can retrieve a lot of informations, getting the latest commits this way isn't easy so I'll try another way.

Using the github API

The github API is a bit simpler and returns JSON objects. I will use JQuery to retrieve repository's data. Remember a repository name is a user/repository string :
var reponame = "rainbru/rainbrurpg"; // The user + repository part of the URL
var divid = "commits"; // The HTML div name we will add commits to

var url = "https://api.github.com/repos/" + reponame + "/commits";

var div = "#"+ divid; // Get the div by id
if($(div).length == 0) {
  throw("Can't find HTML element with '" + divid + "' ID");
}

// Print the latest 10 commits and print
// commit's date and message in console
$.get( url, function( data ) {
  for (i = 0; i < 10; i++) {
    // Get the commit date
    var date = new Date(data[i].commit.author.date);
    console.log(date.toLocaleDateString());
    // Get the commit message
    console.log(data[i].commit.message);
  }).fail(function(qXHR, textStatus, error){
    throw("Cannot get repository '" + url + "' : " + error);
  });

}
We just printed each commit's details in the console but we have the #commits div element and it's pretty simple to print these details in a table.

Comments

Ads