Created
October 26, 2013 08:07
-
-
Save basti1302/7166618 to your computer and use it in GitHub Desktop.
Compare the consumption of a Hypermedia API with and without Traverson
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
var request = require('request') | |
var traverson = require('./traverson') | |
var rootUri = 'https://api.github.com/' | |
// optional: raises the rate limit of the GitHub API from 60 requests to 5000 requests per hour | |
var ghUser = 'basti1302', | |
ghPass = '...' | |
var authOptions = { | |
auth: { | |
user: ghUser, | |
pass: ghPass, | |
sendImmediately: true | |
} | |
} | |
request = request.defaults(authOptions) | |
/* | |
* WITHOUT TRAVERSON: | |
*/ | |
function nextUri(response, link) { | |
var resource = JSON.parse(response.body) | |
return resource[link] | |
} | |
request.get(rootUri, function(err, response) { | |
if (err) { console.log(err); return; } | |
var uri = nextUri(response, 'repository_url') | |
uri = uri.replace(/{owner}/, 'basti1302') | |
uri = uri.replace(/{repo}/, 'traverson') | |
request.get(uri, function(err, response) { | |
if (err) { console.log(err); return; } | |
uri = nextUri(response, 'commits_url') | |
uri = uri.replace(/{\/sha}/, | |
'/5c82c74583ee67eae727466179dd66c91592dd4a') | |
request.get(uri, function(err, response) { | |
if (err) { console.log(err); return; } | |
uri = nextUri(response, 'comments_url') | |
request.get(uri, function(err, response) { | |
if (err) { console.log(err); return; } | |
var resource = JSON.parse(response.body) | |
console.log(resource[0].body) | |
}) | |
}) | |
}) | |
}) | |
/* | |
* WITH TRAVERSON: | |
*/ | |
var api = traverson.json.from(rootUri) | |
api.newRequest() | |
.walk('repository_url', 'commits_url', 'comments_url') | |
.withTemplateParameters({ | |
owner: 'basti1302', | |
repo: 'traverson', | |
sha: '5c82c74583ee67eae727466179dd66c91592dd4a' | |
}).withRequestOptions(authOptions) | |
.getResource(function(err, resource) { | |
if (err) { console.log(err); return; } | |
console.log(resource[0].body) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment