Merge branch 'master' of github.com:visionmedia/express
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Tj Holowaychuk · committed by Tj Holowaychuk · parents 8e3cb61, 6c01e9a · Browse files · 11 files·+279 added−204 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
11 files+279 added−204 removed
- tests:+77 added−43 removed
- other:+202 added−161 removed
Provenance
- Commit
85ea5f6- Tree
5751db5- Author
Tj Holowaychuk <tj@vision-media.ca>- Committer
Tj Holowaychuk <tj@vision-media.ca>- Parent 1
8e3cb61- Parent 2
6c01e9a
11 files changed+279 added−204 removed
modified:bin/express+39 added-39 removed
6 unmodified lines7 var express = require('../')8 , exec = require('child_process').exec9 , program = require('commander')10 , mkdirp = require('mkdirp')11+ , os = require('os')12 , fs = require('fs');13 14 // CLI15 8 unmodified lines24 // Path25 26 var path = program.args.shift() || '.';27 28+// end-of-line code29+30+var eol = 'win32' == os.platform() ? '\r\n' : '\n'31+32 // Template engine33 34 program.template = 'jade';35 if (program.ejs) program.template = 'ejs';17 unmodified lines53 , ''54 , 'exports.index = function(req, res){'55 , ' res.render(\'index\', { title: \'Express\' });'56 , '};'52-].join('\r\n');57+].join(eol);58 59 /**60 * Jade layout template.61 */3 unmodified lines65 , 'html'66 , ' head'67 , ' title= title'68 , ' link(rel=\'stylesheet\', href=\'/stylesheets/style.css\')'64- , ' body!= body'65-].join('\r\n');69+ , ' body'70+ , ' block content'71+].join(eol);72 73 /**74 * Jade index template.75 */76 77 var jadeIndex = [78+ 'extends layout'79+ , ''80+ , 'block content'72- 'h1= title'73- , 'p Welcome to #{title}'74-].join('\r\n');81+ , ' h1= title'82+ , ' p Welcome to #{title}'83+].join(eol);84 85 /**77- * EJS layout template.86+ * EJS index template.87 */88 80-var ejsLayout = [89+var ejsIndex = [90 '<!DOCTYPE html>'91 , '<html>'92 , ' <head>'93 , ' <title><%= title %></title>'94 , ' <link rel=\'stylesheet\' href=\'/stylesheets/style.css\' />'95 , ' </head>'96 , ' <body>'88- , ' <%- body %>'97+ , ' <h1><%= title %></h1>'98+ , ' <p>Welcome to <%= title %></p>'99 , ' </body>'100 , '</html>'91-].join('\r\n');101+].join(eol);102 103 /**94- * EJS index template.95- */96-97-var ejsIndex = [98- '<h1><%= title %></h1>'99- , '<p>Welcome to <%= title %></p>'100- ].join('\r\n');101-102-/**104 * JSHTML layout template.105 */106 107 var jshtmlLayout = [6 unmodified lines114 , ' <body>'115 , ' @write(body)'116 , ' </body>'117 , '</html>'117-].join('\r\n');118+].join(eol);119 120 /**121 * JSHTML index template.122 */123 124 var jshtmlIndex = [125 '<h1>@write(title)</h1>'126 , '<p>Welcome to @write(title)</p>'126- ].join('\r\n');127+ ].join(eol);128 129 /**130 * Default css template.131 */6 unmodified lines138 , ''139 , 'a {'140 , ' color: #00B7FF;'141 , '}'141-].join('\r\n');142+].join(eol);143 144 /**145 * Default less template.146 */6 unmodified lines153 , ''154 , 'a {'155 , ' color: #00B7FF;'156 , '}'156-].join('\r\n');157+].join(eol);158 159 /**160 * Default stylus template.161 */3 unmodified lines165 , ' padding: 50px'166 , ' font: 14px "Lucida Grande", Helvetica, Arial, sans-serif'167 , 'a'168 , ' color: #00B7FF'168-].join('\r\n');169+].join(eol);170 171 /**172 * App template.173 */7 unmodified lines181 , 'var express = require(\'express\')'182 , ' , routes = require(\'./routes\')'183 , ' , http = require(\'http\');'184 , ''184- , 'var app = module.exports = express();'185+ , 'var app = express();'186 , ''187 , 'app.configure(function(){'188 , ' app.set(\'views\', __dirname + \'/views\');'189 , ' app.set(\'view engine\', \':TEMPLATE\');'12 unmodified lines202 , 'app.get(\'/\', routes.index);'203 , ''204 , 'http.createServer(app).listen(3000);'205 , ''205- , 'console.log("Express server listening for connections");'206+ , 'console.log("Express server listening on port 3000");'207 , ''207-].join('\r\n');208+].join(eol);209 210 // Generate application211 212 (function createApplication(path) {48 unmodified lines261 262 mkdir(path + '/views', function(){263 switch (program.template) {264 case 'ejs':264- write(path + '/views/layout.ejs', ejsLayout);265 write(path + '/views/index.ejs', ejsIndex);266 break;267 case 'jade':268 write(path + '/views/layout.jade', jadeLayout);9 unmodified lines278 279 // CSS Engine support280 switch (program.css) {281 case 'stylus':282- app = app.replace('{css}', '\r\n app.use(require(\'stylus\').middleware({ src: __dirname + \'/public\' }));');282+ app = app.replace('{css}', eol + ' app.use(require(\'stylus\').middleware({ src: __dirname + \'/public\' }));');283 break;284 default:285 app = app.replace('{css}', '');286 }287 288 // Session support289 app = app.replace('{sess}', program.sessions290- ? '\n app.use(express.cookieParser(\'your secret here\'));\n app.use(express.session());'290+ ? eol + ' app.use(express.cookieParser(\'your secret here\'));' + eol + ' app.use(express.session());'291 : '');292 293 // Template support294 app = app.replace(':TEMPLATE', program.template);295 296 // package.json297- var json = '{\n';298- json += ' "name": "application-name"\n';299- json += ' , "version": "0.0.1"\n';300- json += ' , "private": true\n';301- json += ' , "dependencies": {\n';302- json += ' "express": "' + express.version + '"\n';303- if (program.css) json += ' , "' + program.css + '": ">= 0.0.1"\n';304- if (program.template) json += ' , "' + program.template + '": ">= 0.0.1"\n';305- json += ' }\n';297+ var json = '{' + eol;298+ json += ' "name": "application-name"' + eol;299+ json += ' , "version": "0.0.1"' + eol;300+ json += ' , "private": true' + eol;301+ json += ' , "dependencies": {' + eol;302+ json += ' "express": "' + express.version + '"' + eol;303+ if (program.css) json += ' , "' + program.css + '": ">= 0.0.1"' + eol;304+ if (program.template) json += ' , "' + program.template + '": ">= 0.0.1"' + eol;305+ json += ' }' + eol;306 json += '}';307 308 309 write(path + '/package.json', json);55 unmodified linesadded:examples/cookie-sessions/index.js+47 added
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
/** * Module dependencies. */
var express = require('../../');
var app = module.exports = express();
/** * Cookie session middleware using the given cookie `name`. * * Here we simply check for a signed cookie of the same name, * then save the object as JSON on response, again as a signed cookie. */
function cookieSessions(name) { return function(req, res, next) { req.session = req.signedCookies[name] || {};
res.on('header', function(){ res.signedCookie(name, req.session); });
next(); }}
// for this we need cookie support! this will// populate req.{signedCookies,cookies}()
app.use(express.cookieParser('manny is cool'));app.use(cookieSessions('sid'));app.use(count);
// do something with our session
function count(req, res) { req.session.count = req.session.count || 0; var n = req.session.count++; res.send('viewed ' + n + ' times\n');}
if (!module.parent) { app.listen(3000); console.log('Express server listening on port 3000');}No newline at end of filedeleted:examples/web-service/app.js-121 removed
1-2-/**3- * Module dependencies.4- */5-6-var express = require('../../lib/express');7-8-var app = express.createServer();9-10-// configuration11-12-// if we wanted to supply more than JSON, we could13-// use something similar to the content-negotiation14-// example.15-16-// here we validate the API key,17-// by mounting this middleware to /api/v118-// meaning only paths prefixed with "/api/v1"19-// will cause this middleware to be invoked20-21-app.use('/api/v1', function(req, res, next){22- var key = req.query['api-key'];23-24- // key isnt present25- if (!key) return next(new Error('api key required'));26-27- // key is invalid28- if (!~apiKeys.indexOf(key)) return next(new Error('invalid api key'));29-30- // all good, store req.key for route access31- req.key = key;32- next();33-});34-35-// position our routes above the error handling middleware,36-// and below our API middleware, since we want the API validation37-// to take place BEFORE our routes38-app.use(app.router);39-40-// middleware with an arity of 4 are considered41-// error handling middleware. When you next(err)42-// it will be passed through the defined middleware43-// in order, but ONLY those with an arity of 4, ignoring44-// regular middleware.45-app.use(function(err, req, res, next){46- // whatever you want here, feel free to populate47- // properties on `err` to treat it differently in here,48- // or when you next(err) set res.statusCode= etc.49- res.send(500, { error: err.message });50-});51-52-// our custom JSON 404 middleware. Since it's placed last53-// it will be the last middleware called, if all others54-// invoke next() and do not respond.55-app.use(function(req, res){56- res.send(404, { error: "Lame, can't find that" });57-});58-59-/**60- * Generate our unique identifier.61- */62-63-function uid() {64- return [65- Math.random() * 0xffff | 066- , Math.random() * 0xffff | 067- , Math.random() * 0xffff | 068- , Date.now()69- ].join('-');70-}71-72-// map of valid api keys, typically mapped to73-// account info with some sort of database like redis.74-// api keys do _not_ serve as authentication, merely to75-// track API usage or help prevent malicious behavior etc.76-77-var apiKeys = [uid(), uid(), uid()];78-79-console.log('valid keys:\n ', apiKeys.join('\n '));80-81-// these two objects will serve as our faux database82-83-var repos = [84- { name: 'express', url: 'http://github.com/visionmedia/express' }85- , { name: 'stylus', url: 'http://github.com/learnboost/stylus' }86- , { name: 'cluster', url: 'http://github.com/learnboost/cluster' }87-];88-89-var users = [90- { name: 'tobi' }91- , { name: 'loki' }92- , { name: 'jane' }93-];94-95-var userRepos = {96- tobi: [repos[0], repos[1]]97- , loki: [repos[1]]98- , jane: [repos[2]]99-};100-101-// we now can assume the api key is valid,102-// and simply expose the data103-104-app.get('/api/v1/users', function(req, res, next){105- res.send(users);106-});107-108-app.get('/api/v1/repos', function(req, res, next){109- res.send(repos);110-});111-112-app.get('/api/v1/user/:name/repos', function(req, res, next){113- var name = req.params.name114- , user = userRepos[name];115- 116- if (user) res.send(user);117- else next();118-});119-120-app.listen(3000);121-console.log('Express server listening on port 3000');added:examples/web-service/index.js+115 added
1+2+/**3+ * Module dependencies.4+ */5+6+var express = require('../../');7+8+var app = module.exports = express();9+10+// create an error with .status. we11+// can then use the property in our12+// custom error handler (Connect repects this prop as well)13+14+function error(status, msg) {15+ var err = new Error(msg);16+ err.status = status;17+ return err;18+}19+20+// if we wanted to supply more than JSON, we could21+// use something similar to the content-negotiation22+// example.23+24+// here we validate the API key,25+// by mounting this middleware to /api26+// meaning only paths prefixed with "/api"27+// will cause this middleware to be invoked28+29+app.use('/api', function(req, res, next){30+ var key = req.query['api-key'];31+32+ // key isnt present33+ if (!key) return next(error(400, 'api key required'));34+35+ // key is invalid36+ if (!~apiKeys.indexOf(key)) return next(error(401, 'invalid api key'));37+38+ // all good, store req.key for route access39+ req.key = key;40+ next();41+});42+43+// position our routes above the error handling middleware,44+// and below our API middleware, since we want the API validation45+// to take place BEFORE our routes46+app.use(app.router);47+48+// middleware with an arity of 4 are considered49+// error handling middleware. When you next(err)50+// it will be passed through the defined middleware51+// in order, but ONLY those with an arity of 4, ignoring52+// regular middleware.53+app.use(function(err, req, res, next){54+ // whatever you want here, feel free to populate55+ // properties on `err` to treat it differently in here.56+ res.send(err.status || 500, { error: err.message });57+});58+59+// our custom JSON 404 middleware. Since it's placed last60+// it will be the last middleware called, if all others61+// invoke next() and do not respond.62+app.use(function(req, res){63+ res.send(404, { error: "Lame, can't find that" });64+});65+66+// map of valid api keys, typically mapped to67+// account info with some sort of database like redis.68+// api keys do _not_ serve as authentication, merely to69+// track API usage or help prevent malicious behavior etc.70+71+var apiKeys = ['foo', 'bar', 'baz'];72+73+// these two objects will serve as our faux database74+75+var repos = [76+ { name: 'express', url: 'http://github.com/visionmedia/express' }77+ , { name: 'stylus', url: 'http://github.com/learnboost/stylus' }78+ , { name: 'cluster', url: 'http://github.com/learnboost/cluster' }79+];80+81+var users = [82+ { name: 'tobi' }83+ , { name: 'loki' }84+ , { name: 'jane' }85+];86+87+var userRepos = {88+ tobi: [repos[0], repos[1]]89+ , loki: [repos[1]]90+ , jane: [repos[2]]91+};92+93+// we now can assume the api key is valid,94+// and simply expose the data95+96+app.get('/api/users', function(req, res, next){97+ res.send(users);98+});99+100+app.get('/api/repos', function(req, res, next){101+ res.send(repos);102+});103+104+app.get('/api/user/:name/repos', function(req, res, next){105+ var name = req.params.name106+ , user = userRepos[name];107+ 108+ if (user) res.send(user);109+ else next();110+});111+112+if (!module.parent) {113+ app.listen(3000);114+ console.log('Express server listening on port 3000');115+}modified:lib/response.js+1 added-1 removed
410 unmodified lines411 res.cookie = function(name, val, options){412 options = options || {};413 if ('object' == typeof val) val = 'j:' + JSON.stringify(val);414 if ('maxAge' in options) options.expires = new Date(Date.now() + options.maxAge);415- if (undefined === options.path) options.path = '/';415+ if (null == options.path) options.path = '/';416 var cookie = utils.serializeCookie(name, val, options);417 this.header('Set-Cookie', cookie);418 return this;419 };157 unmodified linesmodified:test/acceptance/ejs.js+3 added-3 removed
8 unmodified lines910111213141513141516171819208 unmodified lines .get('/') .end(function(res){ res.should.have.status(200); res.should.have.header('Content-Type', 'text/html; charset=utf-8'); res.body.should.include.string('<li>tobi tobi@learnboost.com</li>'); res.body.should.include.string('<li>loki loki@learnboost.com</li>'); res.body.should.include.string('<li>jane jane@learnboost.com</li>'); res.body.should.include('<li>tobi tobi@learnboost.com</li>'); res.body.should.include('<li>loki loki@learnboost.com</li>'); res.body.should.include('<li>jane jane@learnboost.com</li>'); done(); }); }) })})added:test/acceptance/web-service.js+48 added
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
var request = require('../support/http') , app = require('../../examples/web-service');
describe('web-service', function(){ describe('GET /api/users', function(){ describe('without an api key', function(){ it('should respond with 400 bad request', function(done){ request(app) .get('/api/users') .expect(400, done); }) })
describe('with an invalid api key', function(){ it('should respond with 401 unauthorized', function(done){ request(app) .get('/api/users?api-key=rawr') .expect(401, done); }) })
describe('with a valid api key', function(){ it('should respond users json', function(done){ request(app) .get('/api/users?api-key=foo') .end(function(res){ res.should.be.json; res.body.should.equal('[{"name":"tobi"},{"name":"loki"},{"name":"jane"}]'); done(); }); }) }) })
describe('when requesting an invalid route', function(){ it('should respond with 404 json', function(done){ request(app) .get('/api/something?api-key=bar') .end(function(res){ res.should.have.status(404); res.should.be.json; res.body.should.equal('{"error":"Lame, can\'t find that"}'); done(); }); }) })})No newline at end of filemodified:test/exports.js+3 added-3 removed
13 unmodified lines141516171819201819202122232445 unmodified lines13 unmodified lines }) it('should expose HTTP methods', function(){ express.methods.should.be.an.instanceof(Array); express.methods.should.contain('get'); express.methods.should.contain('put'); express.methods.should.contain('post'); express.methods.should.include('get'); express.methods.should.include('put'); express.methods.should.include('post'); }) it('should expose Router', function(){ express.Router.should.be.a('function');45 unmodified linesadded:test/regression.js+22 added
12345678910111213141516171819202122
var express = require('../') , request = require('./support/http');
describe('throw after .end()', function(){ it('should fail gracefully', function(done){ var app = express();
app.get('/', function(req, res){ res.end('yay'); throw new Error('boom'); });
request(app) .get('/') .end(function(res){ res.should.have.status(200); res.body.should.equal('yay'); done(); }); })})modified:test/res.clearCookie.js-18 removed
17 unmodified lines181920212223242526272829303132333435363738392223242516 unmodified lines17 unmodified lines res.headers['set-cookie'].should.eql([val]); done(); }) }) // it('should default path to "root"', function(done){ // var app = express(); // // app.set('root', '/admin'); // // app.use(function(req, res){ // res.clearCookie('sid').end(); // }); // // request(app) // .get('/') // .end(function(res){ // var val = 'sid=; path=/admin; expires=Thu, 01 Jan 1970 00:00:00 GMT'; // res.headers['set-cookie'].should.eql([val]); // done(); // }) // }) }) describe('.clearCookie(name, options)', function(){ it('should set the given params', function(done){16 unmodified linesmodified:test/res.cookie.js+1 added-19 removed
36 unmodified lines37 done();38 })39 })40 41- // it('should default path to "root"', function(done){42- // var app = express();43- // 44- // app.set('root', '/admin');45- // 46- // app.use(function(req, res){47- // res.cookie('name', 'tobi').end();48- // });49- // 50- // request(app)51- // .get('/')52- // .end(function(res){53- // var val = ['name=tobi; path=/admin'];54- // res.headers['set-cookie'].should.eql(val);55- // done();56- // })57- // })58- 41 it('should allow multiple calls', function(done){42 var app = express();43 44 app.use(function(req, res){41 unmodified lines86 87 request(app)88 .get('/')89 .end(function(res){108- res.headers['set-cookie'][0].should.not.include.string('Thu, 01 Jan 1970 00:00:01 GMT');90+ res.headers['set-cookie'][0].should.not.include('Thu, 01 Jan 1970 00:00:01 GMT');91 done();92 })93 })94 })2 unmodified lines