app.js
This file
Path
examples/github/app.js
113 lines · 2.2 KiB · JavaScript
Last changed by
fixed github exampleTJ Holowaychukbefore adoptionda61d8b
History of this fileTake it
The walk stopped after 200 commits: lines older than f7b6dde point at it.
refactored previous commitTj Holowaychukbefore adoptionf7b6dde
lines 1–8why, one step back12/**3 * Module dependencies.4 */56var express = require('../../lib/express')7 , http = require('http');8fixed github exampleTJ Holowaychukbefore adoptionda61d8b
line 9why, one step back9var app = express();refactored previous commitTj Holowaychukbefore adoptionf7b6dde
lines 10–113why, one step back1011// Expose our views1213app.set('views', __dirname + '/views');14app.set('view engine', 'jade');1516/**17 * Request github json api `path`.18 *19 * @param {String} path20 * @param {Function} fn21 * @api public22 */2324function request(path, fn){25 var client = http.createClient(80, 'github.com')26 , req = client.request('GET', '/api/v2/json' + path, { Host: 'github.com' });27 req.on('response', function(res){28 res.body = '';29 res.on('data', function(chunk){ res.body += chunk; });30 res.on('end', function(){31 try {32 fn(null, JSON.parse(res.body));33 } catch (err) {34 fn(err);35 }36 });37 });38 req.end();39}4041/**42 * Sort repositories by watchers desc.43 *44 * @param {Array} repos45 * @api public46 */4748function sort(repos){49 return repos.sort(function(a, b){50 if (a.watchers == b.watchers) return 0;51 if (a.watchers > b.watchers) return -1;52 if (a.watchers < b.watchers) return 1;53 });54}5556/**57 * Tally up total watchers.58 *59 * @param {Array} repos60 * @return {Number}61 * @api public62 */6364function totalWatchers(repos) {65 return repos.reduce(function(sum, repo){66 return sum + repo.watchers;67 }, 0);68}6970/**71 * Default to my user name :)72 */7374app.get('/', function(req, res){75 res.redirect('/repos/visionmedia');76});7778/**79 * Display repos.80 */8182app.get('/repos/*', function(req, res, next){83 var names = req.params[0].split('/')84 , users = [];85 (function fetchData(name){86 // We have a user name87 if (name) {88 console.log('... fetching \x1b[33m%s\x1b[0m', name);89 request('/repos/show/' + name, function(err, user){90 if (err) {91 next(err)92 } else {93 user.totalWatchers = totalWatchers(user.repositories);94 user.repos = sort(user.repositories);95 user.name = name;96 users.push(user);97 fetchData(names.shift());98 }99 });100 // No more users101 } else {102 console.log('... done');103 res.render('index', { users: users });104 }105 })(names.shift());106});107108// Serve statics from ./public109app.use(express.static(__dirname + '/public'));110111// Listen on port 3000112app.listen(3000);113console.log('Express app started on port 3000');