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
Provenance
- Commit
547d18c- Tree
ebe2818- Author
Tj Holowaychuk <tj@vision-media.ca>- Committer
Tj Holowaychuk <tj@vision-media.ca>- Parent 1
f183a81- Parent 2
e44c874
30 files changed+711 added−217 removed
modified:examples/blog/app.js+6 added-13 removed
1234566788910101111121315141517181920212216171819272820212223242512 unmodified lines
/** * Module dependencies. */
var express = require('../../lib/express');var express = require('../../') , app = express();
var app = module.exports = express.createServer();// config
// Config
app.set('views', __dirname + '/views');app.set('view engine', 'jade');
// mount hook// middleware
app.mounted(function(other){ console.log('ive been mounted!');});
// Middleware
app.configure(function(){ app.use(express.logger('dev')); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(express.cookieParser()); app.use(express.session({ secret: 'keyboard cat' })); app.use(express.cookieParser('keyboard cat')); app.use(express.session()); app.use(require('./middleware/locals')); app.use(messages()); app.use(app.router); app.use(express.static(__dirname + '/public'));12 unmodified linesmodified:examples/content-negotiation/app.js+6 added-4 removed
12345667889910111213141516171819202122232413 unmodified lines383940414042434445463 unmodified lines
/** * Module dependencies. */
var express = require('../../lib/express');var express = require('../../') , app = express();
var app = express.createServer();
var users = [ { name: 'tobi' } , { name: 'loki' } , { name: 'jane' }];
function provides(type) { return function(req, res, next){ if (req.accepts(type)) return next(); // invoking next() with "route" will // skip passed all remaining middleware // for this route (if any). next('route'); }}
13 unmodified lines
// curl http://localhost:3000/users -H "Accept: text/plain"
app.get('/users', function(req, res, next){ res.contentType('txt'); res.type('txt'); res.send(users.map(function(user){ return user.name; }).join(', '));});3 unmodified linesmodified:examples/cookies/app.js+18 added-12 removed
123456678891011913141011121314151616171718191920212021222324252627282930313219 unmodified lines
/** * Module dependencies. */
var express = require('../../lib/express');var express = require('../../') , app = express();
var app = express.createServer( // Place default Connect favicon above logger so it is not in // the logging output express.favicon(),
// Custom logger format express.logger({ format: '\x1b[36m:method\x1b[0m \x1b[90m:url\x1b[0m :response-time' }),// add favicon() before logger() so// GET /favicon.ico requests are not// logged, because this middleware// reponds to /favicon.ico and does not// call next()app.use(express.favicon());
// Provides req.cookies express.cookieParser(),// custom log formatapp.use(express.logger(':method :url'));
// Parses x-www-form-urlencoded request bodies (and json) express.bodyParser());// parses request cookies, populating// req.cookies and req.signedCookies// when the secret is passed, used // for signing the cookies.app.use(express.cookieParser('my secret here'));
// parses json, x-www-form-urlencoded, and multipart/form-dataapp.use(express.bodyParser());
app.get('/', function(req, res){ if (req.cookies.remember) { res.send('Remembered :). Click to <a href="/forget">forget</a>!.'); } else {19 unmodified linesmodified:examples/downloads/app.js+12 added-21 removed
1234566788991011124 unmodified lines1718192022232425262728292131323334353637382223242526272829423031323334353645373839402 unmodified lines
/** * Module dependencies. */
var express = require('../../lib/express');var express = require('../../') , app = express();
var app = express.createServer();
app.get('/', function(req, res){ res.send('<ul>' + '<li>Download <a href="/files/amazing.txt">amazing.txt</a>.</li>' + '<li>Download <a href="/files/missing.txt">missing.txt</a>.</li>'4 unmodified lines// but here we name it :fileapp.get('/files/:file(*)', function(req, res, next){ var file = req.params.file , path = __dirname + '/files/' + file; // either res.download(path) and let // express handle failures, or provide // a callback as shown below res.download(path, function(err){ // if an error occurs in this callback // the file most likely does not exist, // and it's safe to respond or next(err) if (err) return next(err);
// the file has been transferred, do not respond // from here, though you may use this callback // for stats etc. console.log('transferred %s', path); }, function(err){ // this second optional callback is used when // an error occurs during transmission }); res.download(path);});
// error handling middleware. Because it's// below our routes, you will be able to// "intercept" errors, otherwise Connect// will respond with 500 "Internal Server Error".app.use(function(err, req, res, next){ if ('ENOENT' == err.code) { // log all errors console.error(err.stack);
// special-case 404s if (404 == err.status) { res.send('Cant find that file, sorry!'); } else { // Not a 404 next(err); }});
2 unmodified linesdeleted:examples/ejs/views/users/index.html-3 removed
123<ul id="users"> <%- partial('user', users) %></ul>No newline at end of filedeleted:examples/ejs/views/users/user.html-1 removed
1<li><%= user.name %> <<%= user.email %>></li>No newline at end of filedeleted:examples/ejs/views/layout.html-6 removed
123456<html> <body> <h1>Users</h1> <%- body %> </body></html>No newline at end of fileadded:examples/ejs/views/users.html+6 added
123456<h1>Users</h1><ul id="users"> <% users.forEach(function(user){ %> <li><%= user.name %> <%= user.email %></li> <% }) %></ul>No newline at end of filemodified:examples/ejs/app.js+14 added-5 removed
1 unmodified line2 /**3 * Module dependencies.4 */5 6-var express = require('../../lib/express');6+var express = require('../../')7+ , app = express();8 8-var 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+// system16 10-// Register ejs as .html17+app.engine('.html', require('ejs').__express);18 12-app.register('.html', require('ejs'));13-19 // Optional since express defaults to CWD/views20 21 app.set('views', __dirname + '/views');22+23+// Without this you would need to24+// supply the extension to res.render()25+// ex: res.render('users.html').26 app.set('view engine', 'html');27 28 // Dummy users29 var users = [11 unmodified linesmodified:examples/error/app.js+27 added-8 removed
1 unmodified line2 /**3 * Module dependencies.4 */5 6-var express = require('../../lib/express');6+var express = require('../../')7+ , app = express();8 8-var app = express.createServer();9+app.use(express.logger('dev'));10+app.use(app.router);11 12+// the error handler is strategically13+// placed *below* the app.router; if it14+// were above it would not receive errors15+// from app.get() etc 16+app.use(error);17+18+// 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.23+24+function error(err, req, res, next) {25+ // log it26+ console.error(err.stack);27+28+ // respond with 500 "Internal Server Error".29+ res.send(500);30+}31+32 app.get('/', function(req, res){33 // Caught and passed down to the errorHandler middleware34 throw new Error('something broke!');35 });36 37 app.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 });43 20-// 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 development23-app.use('/', express.errorHandler({ dump: true, stack: true }));24-44 app.listen(3000);45 console.log('app listening on port 3000');modified:examples/error-pages/views/404.jade+5 added-1 removed
1+2+extends error3+4+block content1-h2 Cannot find #{url}5+ h2 Cannot find #{url}modified:examples/error-pages/views/500.jade+10 added-2 removed
1+2+// note that we extend a different3+// layout with jade for 4xx & 5xx4+// responses5+6+extends error7+8+block content1-h1 Error: #{error.message}2-pre= error.stack9+ h1 Error: #{error.message}10+ pre= error.stackadded:examples/error-pages/views/error.jade+6 added
1+html2+ head 3+ title Error4+ body5+ h1 An error occurred!6+ block contentmodified:examples/error-pages/views/index.jade+15 added-11 removed
1+2+extends layout3+4+block content1-h2 Pages Example2-ul3- 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') 403modified:examples/error-pages/views/layout.jade+1 added-1 removed
1 unmodified line2 head 3 title Custom Pages Example4 body5 h1 My Site6- != body6+ block contentmodified:examples/error-pages/app.js+30 added-21 removed
1 2-// Expose modules in ./support for demo purposes3-require.paths.unshift(__dirname + '/../../support');4-2 /**3 * Module dependencies.4 */5 9-var express = require('../../lib/express');6+var express = require('../../')7+ , app = express();8 11-var app = express.createServer();9 app.set('views', __dirname + '/views');10 app.set('view engine', 'jade');11 15-// Serve default connect favicon12 app.use(express.favicon());13+app.use(express.logger('dev'));14 18-// Logger is placed below favicon, so favicon.ico19-// requests will not be logged20-app.use(express.logger('":method :url" :status'));21-15 // "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.21 22 app.use(app.router);23 24 // Since this is the last non-error-handling25 // middleware use()d, we assume 404, as nothing else26 // responded.27 28+// $ curl http://localhost:3000/notfound29+// $ curl http://localhost:3000/notfound -H "Accept: application/json"30+// $ curl http://localhost:3000/notfound -H "Accept: text/plain"31+32 app.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+ }40+41+ // respond with json42+ if (req.accepts('json')) {43+ res.send({ error: 'Not found' });44+ return;45+ }46+47+ // default to plain-text. send()48+ res.type('txt').send('Not found');49 });50 51 // error-handling middleware, take the same form52 // as regular middleware, however they require an6 unmodified lines59 // continue passing the error, only error-handling middleware60 // would remain being executed, however here61 // we simply respond with an error page.62 51-63 app.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 });70 71 // Routes72 20 unmodified linesdeleted:examples/extending-templates/views/users/index.html-8 removed
1-<% page.title = 'Users' %>2-<% script('/javascripts/jquery.js') %>3-<% script('/javascripts/users.js') %>4-5-<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 %> <<%= user.email %>></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
1-2-/**3- * Module dependencies.4- */5-6-var express = require('../../lib/express');7-8-var app = express.createServer();9-10-// Register ejs as .html11-12-app.register('.html', require('ejs'));13-14-// Optional since express defaults to CWD/views15-16-app.set('views', __dirname + '/views');17-app.set('view engine', 'html');18-19-// Dummy users20-var 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-];25-26-// 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.31-app.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- },40-41- // 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- },51-52- // 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-});60-61-app.get('/', function(req, res){62- res.render('users', { users: users });63-});64-65-app.listen(3000);66-console.log('Express app started on port 3000');modified:lib/request.js+106 added-20 removed
87 unmodified lines88 * @api public89 */90 91 req.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 };99 100 /**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 lines123 * @api public124 */125 126 req.accepts = function(type){130- var accept = this.header('Accept')131- , type = String(type);127+ return utils.accepts(type, this.header('Accept'));128+};129 133- // 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+ */138 136- // normalize extensions ".json" -> "json"137- if ('.' == type[0]) type = type.substr(1);139+req.acceptsCharset = function(charset){140+ var accepted = this.acceptedCharsets;141+ return accepted.length142+ ? ~accepted.indexOf(charset)143+ : true;144+};145 139- // 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+ */154 142- // check if we have a direct match143- if (~accept.indexOf(type)) return true;144-145- // check if we have type/*146- type = type.split('/')[0] + '/*';147- return !! ~accept.indexOf(type);155+req.acceptsLanguage = function(lang){156+ var accepted = this.acceptedLanguages;157+ return accepted.length158+ ? ~accepted.indexOf(lang)159+ : true;160 };161 162 /**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+ */180+181+req.__defineGetter__('accepted', function(){182+ var accept = this.header('Accept');183+ return accept184+ ? utils.parseAccept(accept)185+ : [];186+});187+188+/**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+ */200+201+req.__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+});211+212+/**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+ */224+225+req.__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+});235+236+/**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=12225 unmodified linesmodified:lib/response.js+3 added-1 removed
208 unmodified lines209 // cast ENOENT210 if ('ENOENT' == err.code) err = 404;211 212 // coerce numeric error to an Error213+ // TODO: remove214+ // TODO: remove docs for headerSent?215 if ('number' == typeof err) err = utils.error(err);216 217 // ditch content-disposition to prevent funky responses218 if (!self.headerSent) self.removeHeader('Content-Disposition');20 unmodified lines239 *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} fn351 unmodified linesmodified:lib/utils.js+107 added
4 unmodified lines5 * MIT Licensed6 */7 8 /**9+ * Module dependencies.10+ */11+12+var mime = require('mime');13+14+/**15 * Check if `path` looks absolute.16 *17 * @param {String} path18 * @return {Boolean}47 unmodified lines66 .replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2">$1</a>');67 };68 69 /**70+ * Check if `type` is acceptable based on71+ * the given `str`.72+ *73+ * @param {String} type74+ * @param {String} str75+ * @return {Boolean}76+ * @api public77+ */78+79+exports.accepts = function(type, str){80+ // accept anything when Accept is not present81+ if (!str) return true;82+83+ // resolve mime84+ if (!~type.indexOf('/')) type = mime.lookup(type);85+86+ // split type/subtype87+ type = type.split('/');88+89+ // parse90+ var accepted = exports.parseAccept(str)91+ , len = accepted.length92+ , obj93+ , ok;94+95+ 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+ }101+102+ return false;103+};104+105+/**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+ */116+117+exports.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+};127+128+/**129+ * Parse quality `str`, returning an130+ * array of objects with `.value` and131+ * `.quality`.132+ *133+ * @param {Type} name134+ * @return {Type}135+ * @api public136+ */137+138+exports.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+};149+150+/**151+ * Parse quality `str` returning an152+ * object with `.value` and `.quality`.153+ *154+ * @param {String} str155+ * @return {Object}156+ * @api private157+ */158+159+function quality(str) {160+ var parts = str.split(/ *; */)161+ , val = parts[0];162+163+ var q = parts[1]164+ ? parseFloat(parts[1].split(/ *= */)[1])165+ : 1;166+167+ return { value: val, quality: q };168+}169+170+/**171 * Escape special characters in the given string of html.172 *173 * @param {String} html174 * @return {String}10 unmodified linesadded:test/req.accepted.js+37 added
1+2+var express = require('../')3+ , request = require('./support/http');4+5+describe('req', function(){6+ describe('.accepted', function(){7+ it('should return an array of accepted media types', function(done){8+ var app = express();9+10+ 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+ });15+16+ request(app)17+ .get('/')18+ .set('Accept', 'text/html;q=.5, application/json')19+ .expect(200, done);20+ })21+22+ describe('when Accept is not present', function(){23+ it('should default to []', function(done){24+ var app = express();25+26+ app.use(function(req, res){27+ req.accepted.should.have.length(0);28+ res.end();29+ });30+31+ request(app)32+ .get('/')33+ .expect(200, done);34+ })35+ })36+ })37+})added:test/req.acceptedCharsets.js+37 added
1+2+var express = require('../')3+ , request = require('./support/http');4+5+describe('req', function(){6+ describe('.acceptedCharsets', function(){7+ it('should return an array of accepted charsets', function(done){8+ var app = express();9+10+ 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+ });15+16+ request(app)17+ .get('/')18+ .set('Accept-Charset', 'iso-8859-5;q=.2, unicode-1-1;q=0.8')19+ .expect(200, done);20+ })21+22+ describe('when Accept-Charset is not present', function(){23+ it('should default to []', function(done){24+ var app = express();25+26+ app.use(function(req, res){27+ req.acceptedCharsets.should.have.length(0);28+ res.end();29+ });30+31+ request(app)32+ .get('/')33+ .expect(200, done);34+ })35+ })36+ })37+})added:test/req.acceptedLanguages.js+37 added
1+2+var express = require('../')3+ , request = require('./support/http');4+5+describe('req', function(){6+ describe('.acceptedLanguages', function(){7+ it('should return an array of accepted languages', function(done){8+ var app = express();9+10+ app.use(function(req, res){11+ req.acceptedLanguages[0].should.equal('en-us');12+ req.acceptedLanguages[1].should.equal('en');13+ res.end();14+ });15+16+ request(app)17+ .get('/')18+ .set('Accept-Language', 'en;q=.5, en-us')19+ .expect(200, done);20+ })21+22+ describe('when Accept-Language is not present', function(){23+ it('should default to []', function(done){24+ var app = express();25+26+ app.use(function(req, res){27+ req.acceptedLanguages.should.have.length(0);28+ res.end();29+ });30+31+ request(app)32+ .get('/')33+ .expect(200, done);34+ })35+ })36+ })37+})added:test/req.accepts.js+45 added
1+2+var express = require('../')3+ , request = require('./support/http');4+5+describe('req', function(){6+ describe('.accepts(type)', function(){7+ it('should return true when Accept is not present', function(done){8+ var app = express();9+10+ app.use(function(req, res, next){11+ res.end(req.accepts('json') ? 'yes' : 'no');12+ });13+14+ request(app)15+ .get('/')16+ .expect('yes', done);17+ })18+ 19+ it('should return true when present', function(done){20+ var app = express();21+22+ app.use(function(req, res, next){23+ res.end(req.accepts('json') ? 'yes' : 'no');24+ });25+26+ 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();34+35+ app.use(function(req, res, next){36+ res.end(req.accepts('json') ? 'yes' : 'no');37+ });38+39+ request(app)40+ .get('/')41+ .set('Accept', 'text/html')42+ .expect('no', done);43+ })44+ })45+})added:test/req.acceptsCharset.js+49 added
1+2+var express = require('../')3+ , request = require('./support/http');4+5+describe('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();10+11+ app.use(function(req, res, next){12+ res.end(req.acceptsCharset('utf-8') ? 'yes' : 'no');13+ });14+15+ 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();24+25+ app.use(function(req, res, next){26+ res.end(req.acceptsCharset('utf-8') ? 'yes' : 'no');27+ });28+29+ 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();37+38+ app.use(function(req, res, next){39+ res.end(req.acceptsCharset('utf-8') ? 'yes' : 'no');40+ });41+42+ 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 lines27 it('should escape html entities', function(){28 utils.escape('<script>foo & "bar"')29 .should.equal('<script>foo & "bar"')30 })31+})32+33+describe('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 }]);42+43+ 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+})74+75+describe('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+})86+87+describe('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+ })108+109+ 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;159+160+ utils.accepts('html', '*/html')161+ .should.be.true;162+ })163+ })164 })modified:package.json+1 added-1 removed
17 unmodified lines18 },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