app.js
This file
Path
examples/github/app.js
103 lines · 2.1 KiB · JavaScript
Last changed by
Removed more use("/", ...)sTj Holowaychukbefore adoption8a36c54
History of this fileTake it
Merge branch 'github' into connectTj Holowaychukbefore adoption59ac3d1
lines 1–9why, one step back12/**3 * Module dependencies.4 */56var express = require('./../../lib/express'),7 connect = require('connect'),8 http = require('http');9Removed connect.redirect()Tj Holowaychukbefore adoption0fce93b
line 10why, one step back10var app = express.createServer();Merge branch 'github' into connectTj Holowaychukbefore adoption59ac3d1
lines 11–99why, one step back1112// Expose our views1314app.set('views', __dirname + '/views');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.addListener('response', function(res){28 res.body = '';29 res.addListener('data', function(chunk){ res.body += chunk; });30 res.addListener('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/:user', function(req, res, params, next){83 var name = params.user;84 request('/repos/show/' + name, function(err, user){85 if (err) {86 next(err)87 } else {88 res.render('index.jade', {89 locals: {90 totalWatchers: totalWatchers(user.repositories),91 repos: sort(user.repositories),92 name: name93 }94 });95 }96 });97});9899// Serve statics from ./publicRemoved more use("/", ...)sTj Holowaychukbefore adoption8a36c54
line 100why, one step back100app.use(connect.staticProvider(__dirname + '/public'));Merge branch 'github' into connectTj Holowaychukbefore adoption59ac3d1
lines 101–103why, one step back101102// Listen on port 3000103app.listen(3000);