Skip to content
Myr

merged

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 f183a81, e44c874 · Browse files · 30 files+711 added−217 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

30 files+711 added−217 removed

  • tests:+338 added−0 removed
  • other:+373 added−217 removed

30 files+711 added−217 removed

modified:examples/blog/app.js+6 added-13 removed
modified:examples/content-negotiation/app.js+6 added-4 removed
modified:examples/cookies/app.js+18 added-12 removed
modified:examples/downloads/app.js+12 added-21 removed
deleted:examples/ejs/views/users/index.html-3 removed
deleted:examples/ejs/views/users/user.html-1 removed
deleted:examples/ejs/views/layout.html-6 removed
added:examples/ejs/views/users.html+6 added
modified:examples/ejs/app.js+14 added-5 removed
1 unmodified line
2/**3 * Module dependencies.4 */56var express = require('../../lib/express');6var express = require('../../')7 , app = express();88var app = express.createServer();9// Register ejs as .html. If we did10// not call this, we would need to11// name our views foo.ejs instead12// of foo.html. The __express method13// is simply a function that engines14// use to hook into the Express view15// system1610// Register ejs as .html17app.engine('.html', require('ejs').__express);1812app.register('.html', require('ejs'));1319// Optional since express defaults to CWD/views2021app.set('views', __dirname + '/views');2223// Without this you would need to24// supply the extension to res.render()25// ex: res.render('users.html').26app.set('view engine', 'html');2728// Dummy users29var users = [
11 unmodified lines
modified:examples/error/app.js+27 added-8 removed
1 unmodified line
2/**3 * Module dependencies.4 */56var express = require('../../lib/express');6var express = require('../../')7 , app = express();88var app = express.createServer();9app.use(express.logger('dev'));10app.use(app.router);1112// the error handler is strategically13// placed *below* the app.router; if it14// were above it would not receive errors15// from app.get() etc 16app.use(error);1718// error handling middleware have an arity of 419// instead of the typical (req, res, next),20// otherwise they behave exactly like regular21// middleware, you may have several of them,22// in different orders etc.2324function error(err, req, res, next) {25 // log it26 console.error(err.stack);2728 // respond with 500 "Internal Server Error".29 res.send(500);30}3132app.get('/', function(req, res){33 // Caught and passed down to the errorHandler middleware34 throw new Error('something broke!');35});3637app.get('/next', function(req, res, next){38 // We can also pass exceptions to next()39 process.nextTick(function(){17 next(new Error('oh no!'))40 next(new Error('oh no!'));41 });42});4320// The errorHandler middleware in this case will dump exceptions to stderr21// as well as show the stack trace in responses, currently handles text/plain,22// text/html, and application/json responses to aid in development23app.use('/', express.errorHandler({ dump: true, stack: true }));2444app.listen(3000);45console.log('app listening on port 3000');
modified:examples/error-pages/views/404.jade+5 added-1 removed
12extends error34block content1h2 Cannot find #{url}5 h2 Cannot find #{url}
modified:examples/error-pages/views/500.jade+10 added-2 removed
12// note that we extend a different3// layout with jade for 4xx & 5xx4// responses56extends error78block content1h1 Error: #{error.message}2pre= error.stack9 h1 Error: #{error.message}10 pre= error.stack
added:examples/error-pages/views/error.jade+6 added
1html2 head 3 title Error4 body5 h1 An error occurred!6 block content
modified:examples/error-pages/views/index.jade+15 added-11 removed
12extends layout34block content1h2 Pages Example2ul3 li 4 | visit 5 a(href="/500") 5006 li7 | visit8 a(href="/404") 4049 li10 | visit11 a(href='/403') 4035 h2 Pages Example6 ul7 li 8 | visit 9 a(href="/500") 50010 li11 | visit12 a(href="/404") 40413 li14 | visit15 a(href='/403') 403
modified:examples/error-pages/views/layout.jade+1 added-1 removed
1 unmodified line
2 head 3 title Custom Pages Example4 body5 h1 My Site6 != body6 block content
modified:examples/error-pages/app.js+30 added-21 removed
12// Expose modules in ./support for demo purposes3require.paths.unshift(__dirname + '/../../support');42/**3 * Module dependencies.4 */59var express = require('../../lib/express');6var express = require('../../')7 , app = express();811var app = express.createServer();9app.set('views', __dirname + '/views');10app.set('view engine', 'jade');1115// Serve default connect favicon12app.use(express.favicon());13app.use(express.logger('dev'));1418// Logger is placed below favicon, so favicon.ico19// requests will not be logged20app.use(express.logger('":method :url" :status'));2115// "app.router" positions our routes 23// specifically above the middleware24// assigned below16// above the middleware defined below,17// this means that Express will attempt18// to match & call routes _before_ continuing19// on, at which point we assume it's a 404 because20// no route has handled the request.2122app.use(app.router);2324// Since this is the last non-error-handling25// middleware use()d, we assume 404, as nothing else26// responded.2728// $ curl http://localhost:3000/notfound29// $ curl http://localhost:3000/notfound -H "Accept: application/json"30// $ curl http://localhost:3000/notfound -H "Accept: text/plain"3132app.use(function(req, res, next){33 // the status option, or res.statusCode = 40434 // are equivalent, however with the option we35 // get the "status" local available as well36 res.render('404', { status: 404, url: req.url });33 // respond with html page34 if (req.accepts('html')) {35 console.log('test');36 res.status(404);37 res.render('404', { url: req.url });38 return;39 }4041 // respond with json42 if (req.accepts('json')) {43 res.send({ error: 'Not found' });44 return;45 }4647 // default to plain-text. send()48 res.type('txt').send('Not found');49});5051// error-handling middleware, take the same form52// as regular middleware, however they require an
6 unmodified lines
59// continue passing the error, only error-handling middleware60// would remain being executed, however here61// we simply respond with an error page.625163app.use(function(err, req, res, next){64 // we may use properties of the error object65 // here and next(err) appropriately, or if66 // we possibly recovered from the error, simply next().56 res.render('500', {57 status: err.status || 50058 , error: err59 });67 res.status(err.status || 500);68 res.render('500', { error: err });69});7071// Routes72
20 unmodified lines
deleted:examples/extending-templates/views/users/index.html-8 removed
1<% page.title = 'Users' %>2<% script('/javascripts/jquery.js') %>3<% script('/javascripts/users.js') %>45<h1>Users</h1>6<ul id="users">7 <%- partial('user', users) %>8</ul>
deleted:examples/extending-templates/views/users/user.html-1 removed
1<li><%= user.name %> &lt;<%= user.email %>&gt;</li>
deleted:examples/extending-templates/views/layout.html-11 removed
1<html>2 <head>3 <title><%- page.title %></title>4 <% for (var i in scripts) { %>5 <script src="<%= scripts[i] %>"></script>6 <% } %>7 </head>8 <body>9 <%- body %>10 </body>11</html>
deleted:examples/extending-templates/app.js-66 removed
12/**3 * Module dependencies.4 */56var express = require('../../lib/express');78var app = express.createServer();910// Register ejs as .html1112app.register('.html', require('ejs'));1314// Optional since express defaults to CWD/views1516app.set('views', __dirname + '/views');17app.set('view engine', 'html');1819// Dummy users20var users = [21 { name: 'tj', email: 'tj@sencha.com' }22 , { name: 'ciaran', email: 'ciaranj@gmail.com' }23 , { name: 'aaron', email: 'aaron.heckmann+github@gmail.com' }24];2526// dynamic helpers are simply functions that are invoked27// per request (once), passed both the request and response28// objects. These can be used for request-specific29// details within a view, such telling the layout which30// scripts to include.31app.dynamicHelpers({32 // by simply returning an object here33 // we can set it's properties such as "page.title"34 // within a view, and it remains specific to that request,35 // so it would be valid to do:36 // page.title = user.name + "'s account"37 page: function() {38 return {};39 },4041 // the scripts array here is assigned once,42 // so by returning a closure, we can use script(path)43 // in a template, instead of something like44 // scripts.push(path).45 script: function(req){46 req._scripts = [];47 return function(path){48 req._scripts.push(path);49 }50 },5152 // to expose our scripts array for iteration within53 // our views (typically the layout), we simply return it54 // here, and since composite types are mutable, it will55 // contain all of the paths pushed with the helper above.56 scripts: function(req){57 return req._scripts;58 }59});6061app.get('/', function(req, res){62 res.render('users', { users: users });63});6465app.listen(3000);66console.log('Express app started on port 3000');
modified:lib/request.js+106 added-20 removed
87 unmodified lines
88 * @api public89 */9091req.get = function(field, param){92 // TODO: rename... add tests, make .get() .header()93 var val = this.header(field);94 if (!val) return '';95 var regexp = new RegExp(param + ' *= *(?:"([^"]+)"|([^;]+))', 'i');96 if (!regexp.exec(val)) return '';97 return RegExp.$1 || RegExp.$2;98};99100/**100 * Check if the _Accept_ header is present, and includes the given `type`.101 * Check if the given `type` is acceptable,102 * otherwise you should respond with 406 "Not Acceptable".103 *102 * When the _Accept_ header is not present `true` is returned. Otherwise103 * the given `type` is matched by an exact match, and then subtypes. You104 * may pass the subtype such as "html" which is then converted internally105 * to "text/html" using the mime lookup table.106 *104 * Examples:105 * 106 * // Accept: text/html107 * req.accepts('html');
15 unmodified lines
123 * @api public124 */125126req.accepts = function(type){130 var accept = this.header('Accept')131 , type = String(type);127 return utils.accepts(type, this.header('Accept'));128};129133 // when not present or "*/*" accept anything134 if (!accept || '*/*' == accept) return true;130/**131 * Check if the given `charset` is acceptable,132 * otherwise you should respond with 406 "Not Acceptable".133 *134 * @param {String} charset135 * @return {Boolean}136 * @api public137 */138136 // normalize extensions ".json" -> "json"137 if ('.' == type[0]) type = type.substr(1);139req.acceptsCharset = function(charset){140 var accepted = this.acceptedCharsets;141 return accepted.length142 ? ~accepted.indexOf(charset)143 : true;144};145139 // allow "html" vs "text/html" etc140 if (!~type.indexOf('/')) type = mime.lookup(type);146/**147 * Check if the given `lang` is acceptable,148 * otherwise you should respond with 406 "Not Acceptable".149 *150 * @param {String} lang151 * @return {Boolean}152 * @api public153 */154142 // check if we have a direct match143 if (~accept.indexOf(type)) return true;144145 // check if we have type/*146 type = type.split('/')[0] + '/*';147 return !! ~accept.indexOf(type);155req.acceptsLanguage = function(lang){156 var accepted = this.acceptedLanguages;157 return accepted.length158 ? ~accepted.indexOf(lang)159 : true;160};161162/**163 * Return an array of Accepted media types164 * ordered from highest quality to lowest.165 *166 * Examples:167 *168 * [ { value: 'application/json',169 * quality: 1,170 * type: 'application',171 * subtype: 'json' },172 * { value: 'text/html',173 * quality: 0.5,174 * type: 'text',175 * subtype: 'html' } ]176 *177 * @return {Array}178 * @api public179 */180181req.__defineGetter__('accepted', function(){182 var accept = this.header('Accept');183 return accept184 ? utils.parseAccept(accept)185 : [];186});187188/**189 * Return an array of Accepted languages190 * ordered from highest quality to lowest.191 *192 * Examples:193 *194 * Accept-Language: en;q=.5, en-us195 * ['en-us', 'en']196 *197 * @return {Array}198 * @api public199 */200201req.__defineGetter__('acceptedLanguages', function(){202 var accept = this.header('Accept-Language');203 return accept204 ? utils205 .parseQuality(accept)206 .map(function(obj){207 return obj.value;208 })209 : [];210});211212/**213 * Return an array of Accepted charsets214 * ordered from highest quality to lowest.215 *216 * Examples:217 *218 * Accept-Charset: iso-8859-5;q=.2, unicode-1-1;q=0.8219 * ['unicode-1-1', 'iso-8859-5']220 *221 * @return {Array}222 * @api public223 */224225req.__defineGetter__('acceptedCharsets', function(){226 var accept = this.header('Accept-Charset');227 return accept228 ? utils229 .parseQuality(accept)230 .map(function(obj){231 return obj.value;232 })233 : [];234});235236/**237 * Return the value of param `name` when present or `defaultValue`.238 *239 * - Checks route placeholders, ex: _/user/:id_240 * - Checks query string params, ex: ?id=12
225 unmodified lines
modified:lib/response.js+3 added-1 removed
208 unmodified lines
209 // cast ENOENT210 if ('ENOENT' == err.code) err = 404;211212 // coerce numeric error to an Error213 // TODO: remove214 // TODO: remove docs for headerSent?215 if ('number' == typeof err) err = utils.error(err);216217 // ditch content-disposition to prevent funky responses218 if (!self.headerSent) self.removeHeader('Content-Disposition');
20 unmodified lines
239 *240 * Optionally providing an alternate attachment `filename`,241 * and optional callback `fn(err)`. The callback is invoked242 * when the data transfer is complete, or when an error has241 * ocurred. Be sure to check `res.sendHeader` if you plan to respond.243 * ocurred. Be sure to check `res.headerSent` if you plan to respond.244 *245 * @param {String} path246 * @param {String|Function} filename or fn247 * @param {Function} fn
351 unmodified lines
modified:lib/utils.js+107 added
4 unmodified lines
5 * MIT Licensed6 */78/**9 * Module dependencies.10 */1112var mime = require('mime');1314/**15 * Check if `path` looks absolute.16 *17 * @param {String} path18 * @return {Boolean}
47 unmodified lines
66 .replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2">$1</a>');67};6869/**70 * Check if `type` is acceptable based on71 * the given `str`.72 *73 * @param {String} type74 * @param {String} str75 * @return {Boolean}76 * @api public77 */7879exports.accepts = function(type, str){80 // accept anything when Accept is not present81 if (!str) return true;8283 // resolve mime84 if (!~type.indexOf('/')) type = mime.lookup(type);8586 // split type/subtype87 type = type.split('/');8889 // parse90 var accepted = exports.parseAccept(str)91 , len = accepted.length92 , obj93 , ok;9495 for (var i = 0; i < len; ++i) {96 obj = accepted[i];97 ok = (type[0] == obj.type || '*' == obj.type)98 && (type[1] == obj.subtype || '*' == obj.subtype);99 if (ok) return true;100 }101102 return false;103};104105/**106 * Parse accept `str`, returning107 * an array objects containing108 * `.type` and `.subtype` along109 * with the values provided by110 * `parseQuality()`.111 *112 * @param {Type} name113 * @return {Type}114 * @api public115 */116117exports.parseAccept = function(str){118 return exports119 .parseQuality(str)120 .map(function(obj){121 var parts = obj.value.split('/');122 obj.type = parts[0];123 obj.subtype = parts[1];124 return obj;125 });126};127128/**129 * Parse quality `str`, returning an130 * array of objects with `.value` and131 * `.quality`.132 *133 * @param {Type} name134 * @return {Type}135 * @api public136 */137138exports.parseQuality = function(str){139 return str140 .split(/ *, */)141 .map(quality)142 .filter(function(obj){143 return obj.quality;144 })145 .sort(function(a, b){146 return b.quality - a.quality;147 });148};149150/**151 * Parse quality `str` returning an152 * object with `.value` and `.quality`.153 *154 * @param {String} str155 * @return {Object}156 * @api private157 */158159function quality(str) {160 var parts = str.split(/ *; */)161 , val = parts[0];162163 var q = parts[1]164 ? parseFloat(parts[1].split(/ *= */)[1])165 : 1;166167 return { value: val, quality: q };168}169170/**171 * Escape special characters in the given string of html.172 *173 * @param {String} html174 * @return {String}
10 unmodified lines
added:test/req.accepted.js+37 added
12var express = require('../')3 , request = require('./support/http');45describe('req', function(){6 describe('.accepted', function(){7 it('should return an array of accepted media types', function(done){8 var app = express();910 app.use(function(req, res){11 req.accepted[0].value.should.equal('application/json');12 req.accepted[1].value.should.equal('text/html');13 res.end();14 });1516 request(app)17 .get('/')18 .set('Accept', 'text/html;q=.5, application/json')19 .expect(200, done);20 })2122 describe('when Accept is not present', function(){23 it('should default to []', function(done){24 var app = express();2526 app.use(function(req, res){27 req.accepted.should.have.length(0);28 res.end();29 });3031 request(app)32 .get('/')33 .expect(200, done);34 })35 })36 })37})
added:test/req.acceptedCharsets.js+37 added
12var express = require('../')3 , request = require('./support/http');45describe('req', function(){6 describe('.acceptedCharsets', function(){7 it('should return an array of accepted charsets', function(done){8 var app = express();910 app.use(function(req, res){11 req.acceptedCharsets[0].should.equal('unicode-1-1');12 req.acceptedCharsets[1].should.equal('iso-8859-5');13 res.end();14 });1516 request(app)17 .get('/')18 .set('Accept-Charset', 'iso-8859-5;q=.2, unicode-1-1;q=0.8')19 .expect(200, done);20 })2122 describe('when Accept-Charset is not present', function(){23 it('should default to []', function(done){24 var app = express();2526 app.use(function(req, res){27 req.acceptedCharsets.should.have.length(0);28 res.end();29 });3031 request(app)32 .get('/')33 .expect(200, done);34 })35 })36 })37})
added:test/req.acceptedLanguages.js+37 added
12var express = require('../')3 , request = require('./support/http');45describe('req', function(){6 describe('.acceptedLanguages', function(){7 it('should return an array of accepted languages', function(done){8 var app = express();910 app.use(function(req, res){11 req.acceptedLanguages[0].should.equal('en-us');12 req.acceptedLanguages[1].should.equal('en');13 res.end();14 });1516 request(app)17 .get('/')18 .set('Accept-Language', 'en;q=.5, en-us')19 .expect(200, done);20 })2122 describe('when Accept-Language is not present', function(){23 it('should default to []', function(done){24 var app = express();2526 app.use(function(req, res){27 req.acceptedLanguages.should.have.length(0);28 res.end();29 });3031 request(app)32 .get('/')33 .expect(200, done);34 })35 })36 })37})
added:test/req.accepts.js+45 added
12var express = require('../')3 , request = require('./support/http');45describe('req', function(){6 describe('.accepts(type)', function(){7 it('should return true when Accept is not present', function(done){8 var app = express();910 app.use(function(req, res, next){11 res.end(req.accepts('json') ? 'yes' : 'no');12 });1314 request(app)15 .get('/')16 .expect('yes', done);17 })18 19 it('should return true when present', function(done){20 var app = express();2122 app.use(function(req, res, next){23 res.end(req.accepts('json') ? 'yes' : 'no');24 });2526 request(app)27 .get('/')28 .set('Accept', 'application/json')29 .expect('yes', done);30 })31 32 it('should return false otherwise', function(done){33 var app = express();3435 app.use(function(req, res, next){36 res.end(req.accepts('json') ? 'yes' : 'no');37 });3839 request(app)40 .get('/')41 .set('Accept', 'text/html')42 .expect('no', done);43 })44 })45})
added:test/req.acceptsCharset.js+49 added
12var express = require('../')3 , request = require('./support/http');45describe('req', function(){6 describe('.acceptsCharset(type)', function(){7 describe('when Accept-Charset is not present', function(){8 it('should return true', function(done){9 var app = express();1011 app.use(function(req, res, next){12 res.end(req.acceptsCharset('utf-8') ? 'yes' : 'no');13 });1415 request(app)16 .get('/')17 .expect('yes', done);18 })19 })20 21 describe('when Accept-Charset is not present', function(){22 it('should return true when present', function(done){23 var app = express();2425 app.use(function(req, res, next){26 res.end(req.acceptsCharset('utf-8') ? 'yes' : 'no');27 });2829 request(app)30 .get('/')31 .set('Accept-Charset', 'foo, bar, utf-8')32 .expect('yes', done);33 })34 35 it('should return false otherwise', function(done){36 var app = express();3738 app.use(function(req, res, next){39 res.end(req.acceptsCharset('utf-8') ? 'yes' : 'no');40 });4142 request(app)43 .get('/')44 .set('Accept-Charset', 'foo, bar')45 .expect('no', done);46 })47 })48 })49})
modified:test/utils.js+133 added
26 unmodified lines
27 it('should escape html entities', function(){28 utils.escape('<script>foo & "bar"')29 .should.equal('&lt;script&gt;foo &amp; &quot;bar&quot;')30 })31})3233describe('utils.parseQuality(str)', function(){34 it('should default quality to 1', function(){35 utils.parseQuality('text/html')36 .should.eql([{ value: 'text/html', quality: 1 }]);37 })38 39 it('should parse qvalues', function(){40 utils.parseQuality('text/html; q=0.5')41 .should.eql([{ value: 'text/html', quality: 0.5 }]);4243 utils.parseQuality('text/html; q=.2')44 .should.eql([{ value: 'text/html', quality: 0.2 }]);45 })46 47 it('should work with messed up whitespace', function(){48 utils.parseQuality('text/html ; q = .2')49 .should.eql([{ value: 'text/html', quality: 0.2 }]);50 })51 52 it('should work with multiples', function(){53 var str = 'da, en;q=.5, en-gb;q=.8';54 var arr = utils.parseQuality(str);55 arr[0].value.should.equal('da');56 arr[1].value.should.equal('en-gb');57 arr[2].value.should.equal('en');58 })59 60 it('should sort by quality', function(){61 var str = 'text/plain;q=.2, application/json, text/html;q=0.5';62 var arr = utils.parseQuality(str);63 arr[0].value.should.equal('application/json');64 arr[1].value.should.equal('text/html');65 arr[2].value.should.equal('text/plain');66 })67 68 it('should exclude those with a quality of 0', function(){69 var str = 'text/plain;q=.2, application/json, text/html;q=0';70 var arr = utils.parseQuality(str);71 arr.should.have.length(2);72 })73})7475describe('utils.parseAccept(str)', function(){76 it('should provide .type', function(){77 var arr = utils.parseAccept('text/html');78 arr[0].type.should.equal('text');79 })80 81 it('should provide .subtype', function(){82 var arr = utils.parseAccept('text/html');83 arr[0].subtype.should.equal('html');84 })85})8687describe('utils.accepts(type, str)', function(){88 describe('when a string is not given', function(){89 it('should return true', function(){90 utils.accepts('text/html')91 .should.be.true;92 })93 })94 95 describe('when a string is empty', function(){96 it('should return true', function(){97 utils.accepts('text/html', '')98 .should.be.true;99 })100 })101 102 describe('when */* is given', function(){103 it('should return true', function(){104 utils.accepts('text/html', 'text/plain, */*')105 .should.be.true;106 })107 })108109 describe('when accepting type/subtype', function(){110 it('should return true when present', function(){111 utils.accepts('text/html', 'text/plain, text/html')112 .should.be.true;113 })114 115 it('should return false otherwise', function(){116 utils.accepts('text/html', 'text/plain, application/json')117 .should.be.false;118 })119 })120 121 describe('when accepting */subtype', function(){122 it('should return true when present', function(){123 utils.accepts('text/html', 'text/*')124 .should.be.true;125 })126 127 it('should return false otherwise', function(){128 utils.accepts('text/html', 'image/*')129 .should.be.false;130 })131 })132 133 describe('when accepting type/*', function(){134 it('should return true when present', function(){135 utils.accepts('text/html', '*/html')136 .should.be.true;137 })138 139 it('should return false otherwise', function(){140 utils.accepts('text/html', '*/json')141 .should.be.false;142 })143 })144 145 describe('when an extension is given', function(){146 it('should return true when present', function(){147 utils.accepts('html', 'text/html, application/json')148 .should.be.true;149 })150 151 it('should return false otherwise', function(){152 utils.accepts('html', 'text/plain, application/json')153 .should.be.false;154 })155 156 it('should support *', function(){157 utils.accepts('html', 'text/*')158 .should.be.true;159160 utils.accepts('html', '*/html')161 .should.be.true;162 })163 })164})
modified:package.json+1 added-1 removed
17 unmodified lines
18 },19 "devDependencies": {20 "connect-form": "0.2.1",21 "ejs": "0.4.2",22 "mocha": "0.0.1",22 "mocha": "*",23 "jade": "0.17.x",24 "stylus": "0.13.0",25 "should": "0.3.2",26 "express-messages": "0.0.2",
10 unmodified lines