My first module

In my previous post, I started a project to create a codeplex plugin for strider. Today, I will take another baby step. Because baby steps are the easiest. Unless you're a baby. A node baby. Ahem.

In order to make it useful, I did a little bit of refactoring. I created a new codeplex.js file, and moved the code that does all the work into it. This will be the place where all calls to codeplex occur. I created a method that takes the user's name as a parameter, and will get their repositories. It also takes a callback function, which by node convention expects two arguments: err and data. Errors will be passed in err, and the results will be passed in data:

function getRepos(user, callback)

Also, after reading about the codeplex api version,

Wait, wait, wait. Seriously Microsoft... you haven't updated the codeplex api in at least 1.5 years?! Have you done any work on it in that time? site in 5 months?! And the last update to the API (to add 3rd party web apps, but no generic webhooks) was 9 months ago?! It is no wonder that github is so much better that even your own teams are using it instead of codeplex. Not that I have a horse in the online code source repository race, but abandonement just seems like a common theme with some of Microsoft's best/most promising/much loved technologies lately.

Anyway, after reading about the codeplex api version, I added the version header to the request options:

var options = {  
  hostname: 'www.codeplex.com',
  path: '/api/users/' + user + '/projects',
  method: 'GET',
  headers: {'x-ms-version': '2012-09-01'}
};

The rest of the code is very similar, but I added functionality to pass along any errors:

var req = https.request(options, function(res) {  
    var json = '';
    res.on('data', function(d) {
        json += d;
    });
    res.on('error', function(err) {
        callback(err, null);
    });
    res.on('end', function() {
        var repos = JSON.parse(json);
        callback(null, repos);
    });
});

req.on('error', function(err) {  
    callback(err, null);
});
req.end();  

The last, and probably most important part was exposing the method as a module. Node's module concept is pretty slick; by exposing it as a module, it makes it really easy to call from other code. Like, really easy (from index.js):

var codeplex = require('./codeplex');

codeplex.getRepos(username, function(err, data) {  
...
});

If you check out the github repo, you'll see I also extended index.js to present a form that you can put in a username to see the codeplex repositories for.

-AH


View or Post Comments