app.js
This file
Path
examples/github/app.js
108 lines · 2.2 KiB · JavaScript
Last changed by
Merge branch 'github' into connectTj Holowaychukbefore adoption59ac3d1
History of this fileTake it
Merge branch 'github' into connectTj Holowaychukbefore adoption59ac3d1
lines 1–108why, one step back12/**3 * Module dependencies.4 */56var express = require('./../../lib/express'),7 connect = require('connect'),8 http = require('http');910// Setup server with redirect middleware,11// providing us with res.redirect()1213var app = express.createServer(14 connect.redirect()15);1617// Expose our views1819app.set('views', __dirname + '/views');2021/**22 * Request github json api `path`.23 *24 * @param {String} path25 * @param {Function} fn26 * @api public27 */2829function request(path, fn){30 var client = http.createClient(80, 'github.com'),31 req = client.request('GET', '/api/v2/json' + path, { Host: 'github.com' });32 req.addListener('response', function(res){33 res.body = '';34 res.addListener('data', function(chunk){ res.body += chunk; });35 res.addListener('end', function(){36 try {37 fn(null, JSON.parse(res.body));38 } catch (err) {39 fn(err);40 }41 });42 });43 req.end();44}4546/**47 * Sort repositories by watchers desc.48 *49 * @param {Array} repos50 * @api public51 */5253function sort(repos){54 return repos.sort(function(a, b){55 if (a.watchers == b.watchers) return 0;56 if (a.watchers > b.watchers) return -1;57 if (a.watchers < b.watchers) return 1;58 });59}6061/**62 * Tally up total watchers.63 *64 * @param {Array} repos65 * @return {Number}66 * @api public67 */6869function totalWatchers(repos) {70 return repos.reduce(function(sum, repo){71 return sum + repo.watchers;72 }, 0);73}7475/**76 * Default to my user name :)77 */7879app.get('/', function(req, res){80 res.redirect('/repos/visionmedia');81});8283/**84 * Display repos.85 */8687app.get('/repos/:user', function(req, res, params, next){88 var name = params.user;89 request('/repos/show/' + name, function(err, user){90 if (err) {91 next(err)92 } else {93 res.render('index.jade', {94 locals: {95 totalWatchers: totalWatchers(user.repositories),96 repos: sort(user.repositories),97 name: name98 }99 });100 }101 });102});103104// Serve statics from ./public105app.use('/', connect.staticProvider(__dirname + '/public'));106107// Listen on port 3000108app.listen(3000);