Merge branch 'refactor/router'
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 805b9ac, 53a16e1 · Browse files · 9 files·+482 added−313 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
9 files+482 added−313 removed
- tests:+248 added−185 removed
- other:+234 added−128 removed
Provenance
- Commit
351f6ab- Tree
35fe937- Author
Tj Holowaychuk <tj@vision-media.ca>- Committer
Tj Holowaychuk <tj@vision-media.ca>- Parent 1
805b9ac- Parent 2
53a16e1
9 files changed+482 added−313 removed
modified:lib/router/index.js+61 added-95 removed
8 unmodified lines9 * Module dependencies.10 */11 12 var utils = require('../utils')13- , parse = require('url').parse;13+ , parse = require('url').parse14+ , _methods = require('./methods')15+ , Route = require('./route');16 17 /**18 * Expose router.19 */20 21 exports = module.exports = router;22 23 /**22- * Supported HTTP / WebDAV methods.24+ * Expose methods.25 */26 25-var _methods = exports.methods = [26- 'get'27- , 'post'28- , 'put'29- , 'delete'30- , 'connect'31- , 'options'32- , 'trace'33- , 'copy'34- , 'lock'35- , 'mkcol'36- , 'move'37- , 'propfind'38- , 'proppatch'39- , 'unlock'40- , 'report'41- , 'mkactivity'42- , 'checkout'43- , 'merge'44-];27+exports.methods = _methods;28 29 /**30 * Provides Sinatra-like routing capabilities.31 *50 unmodified lines82 fn.middleware = middleware;83 84 if (!path) throw new Error(name + ' route requires a path');85 if (!fn) throw new Error(name + ' route ' + path + ' requires a callback');103- var regexp = path instanceof RegExp104- ? path105- : normalizePath(path, keys);106- localRoutes.push({107- fn: fn108- , path: regexp109- , keys: keys110- , orig: path111- , method: name112- });86+87+ var route = new Route(name, path, fn);88+ localRoutes.push(route);89 return self;90 };91 }92 34 unmodified lines127 } else if (!key) {128 // route middleware129 i = 0;130 (function nextMiddleware(err){155- var fn = route.middleware[i++];131+ var fn = route.callback.middleware[i++];132 if ('route' == err) {133 pass(req._route_index + 1);134 } else if (err) {135 next(err);136 } else if (fn) {137 fn(req, res, nextMiddleware);138 } else {163- route.call(self, req, res, function(err){139+ route.callback.call(self, req, res, function(err){140 if (err) {141 next(err);142 } else {143 pass(req._route_index + 1);16 unmodified lines160 }161 })();162 };163 188- router.remove = function(path, method){189- var fns = router.lookup(path, method);190- fns.forEach(function(fn){191- routes[fn.method].splice(fn.index, 1);192- });164+ router.remove = function(path, method, ret){165+ var ret = ret || []166+ , route;167+168+ // method specific remove169+ if (method) {170+ method = method.toUpperCase();171+ if (routes[method]) {172+ for (var i = 0; i < routes[method].length; ++i) {173+ route = routes[method][i];174+ if (path == route.path) {175+ route.index = i;176+ routes[method].splice(i, 1);177+ ret.push(route);178+ --i;179+ }180+ }181+ }182+ // global remove183+ } else {184+ _methods.forEach(function(method){185+ router.remove(path, method, ret);186+ });187+ }188+189+ return ret;190 };191 192 router.lookup = function(path, method, ret){193 ret = ret || [];2 unmodified lines196 if (method) {197 method = method.toUpperCase();198 if (routes[method]) {199 routes[method].forEach(function(route, i){203- if (path == route.orig) {204- var fn = route.fn;205- fn.regexp = route.path;206- fn.keys = route.keys;207- fn.path = route.orig;208- fn.method = route.method;209- fn.index = i;210- ret.push(fn);200+ if (path == route.path) {201+ route.index = i;202+ ret.push(route);203 }204 });205 }206 // global lookup8 unmodified lines215 216 router.match = function(url, method, ret){217 var ret = ret || []218 , i = 0227- , fn219+ , route220 , req;221 222 // method specific matches223 if (method) {224 method = method.toUpperCase();225 req = { url: url, method: method };234- while (fn = match(req, routes, i)) {226+ while (route = match(req, routes, i)) {227 i = req._route_index + 1;228+ route.index = i;236- ret.push(fn);229+ ret.push(route);230 } 231 // global matches232 } else {233 _methods.forEach(function(method){34 unmodified lines268 function optionsFor(path, routes) {269 return _methods.filter(function(method){270 var arr = routes[method.toUpperCase()];271 for (var i = 0, len = arr.length; i < len; ++i) {279- if (arr[i].path.test(path)) return true;272+ if (arr[i].regexp.test(path)) return true;273 }274 }).map(function(method){275 return method.toUpperCase();276 });277 }278 279 /**287- * Normalize the given path string,288- * returning a regular expression.289- *290- * An empty array should be passed,291- * which will contain the placeholder292- * key names. For example "/user/:id" will293- * then contain ["id"].294- *295- * @param {String} path296- * @param {Array} keys297- * @return {RegExp}298- * @api private299- */300-301-function normalizePath(path, keys) {302- path = path303- .concat('/?')304- .replace(/\/\(/g, '(?:/')305- .replace(/(\/)?(\.)?:(\w+)(?:(\(.*?\)))?(\?)?/g, function(_, slash, format, key, capture, optional){306- keys.push(key);307- slash = slash || '';308- return ''309- + (optional ? '' : slash)310- + '(?:'311- + (optional ? slash : '')312- + (format || '') + (capture || '([^/]+?)') + ')'313- + (optional || '');314- })315- .replace(/([\/.])/g, '\\$1')316- .replace(/\*/g, '(.+)');317- return new RegExp('^' + path + '$', 'i');318-}319-320-/**280 * Attempt to match the given request to281 * one of the routes. When successful282 * a route function is returned.283 *6 unmodified lines290 function match(req, routes, i) {291 var captures292 , method = req.method293 , i = i || 0;294+295+ // pass HEAD to GET routes296 if ('HEAD' == method) method = 'GET';297+298+ // routes for this method299 if (routes = routes[method]) {300 var url = parse(req.url)301 , pathname = url.pathname;302+303+ // matching routes304 for (var len = routes.length; i < len; ++i) {305 var route = routes[i]341- , fn = route.fn342- , path = route.path343- , keys = fn.keys = route.keys;306+ , fn = route.callback307+ , path = route.regexp308+ , keys = route.keys;309+310+ // match311 if (captures = path.exec(pathname)) {345- fn.method = method;346- fn.params = [];347- for (var j = 1, len = captures.length; j < len; ++j) {312+ route.params = [];313+ for (var j = 1, l = captures.length; j < l; ++j) {314 var key = keys[j-1],349- val = typeof captures[j] === 'string'315+ val = 'string' == typeof captures[j]316 ? decodeURIComponent(captures[j])317 : captures[j];318 if (key) {353- fn.params[key] = val;319+ route.params[key] = val;320 } else {355- fn.params.push(val);321+ route.params.push(val);322 }323 }324 req._route_index = i;359- return fn;325+ return route;326 }327 }328 }329 }added:lib/router/methods.js+31 added
12345678910111213141516171819202122232425262728293031
/*! * Express - router - methods * Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca> * MIT Licensed */
/** * Supported HTTP / WebDAV methods. */
module.exports = [ 'get' , 'post' , 'put' , 'delete' , 'connect' , 'options' , 'trace' , 'copy' , 'lock' , 'mkcol' , 'move' , 'propfind' , 'proppatch' , 'unlock' , 'report' , 'mkactivity' , 'checkout' , 'merge'];No newline at end of fileadded:lib/router/route.js+64 added
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
/*! * Express - router - Route * Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca> * MIT Licensed */
/** * Expose `Route`. */
module.exports = Route;
/** * Initialize `Route` with the given HTTP `method`, `path`, * and callback `fn`. * * @param {String} method * @param {String} path * @param {Function} fn * @api private */
function Route(method, path, fn) { this.callback = fn; this.path = path; this.regexp = normalize(path, this.keys = []); this.method = method;}
/** * Normalize the given path string, * returning a regular expression. * * An empty array should be passed, * which will contain the placeholder * key names. For example "/user/:id" will * then contain ["id"]. * * @param {String|RegExp} path * @param {Array} keys * @return {RegExp} * @api private */
function normalize(path, keys) { if (path instanceof RegExp) return path; path = path .concat('/?') .replace(/\/\(/g, '(?:/') .replace(/(\/)?(\.)?:(\w+)(?:(\(.*?\)))?(\?)?/g, function(_, slash, format, key, capture, optional){ keys.push(key); slash = slash || ''; return '' + (optional ? '' : slash) + '(?:' + (optional ? slash : '') + (format || '') + (capture || '([^/]+?)') + ')' + (optional || ''); }) .replace(/([\/.])/g, '\\$1') .replace(/\*/g, '(.+)'); return new RegExp('^' + path + '$', 'i');}No newline at end of filemodified:lib/view/view.js+7 added-1 removed
15 unmodified lines16 , fs = require('fs')17 , stat = fs.statSync;18 19 /**20+ * Expose `View`.21+ */22+23+exports = module.exports = View;24+25+/**26 * Require cache.27 */28 29 var cache = {};5 unmodified lines35 * @param {Object} options36 * @api private37 */38 33-var View = exports = module.exports = function View(view, options) {39+function View(view, options) {40 options = options || {};41 this.view = view;42 this.root = options.root;43 this.relative = false !== options.relative;162 unmodified linesmodified:lib/express.js+3 added-1 removed
9 unmodified lines101112131414151617181931 unmodified lines51525354555657585919 unmodified lines9 unmodified lines */
var connect = require('connect') , HTTPSServer = require('./https') , HTTPServer = require('./http'); , HTTPServer = require('./http') , Route = require('./router/route')
/** * Re-export connect auto-loaders. * 31 unmodified lines */
exports.HTTPServer = HTTPServer;exports.HTTPSServer = HTTPSServer;exports.Route = Route;
/** * View extensions. */19 unmodified linesmodified:lib/http.js+53 added-28 removed
16 unmodified lines17 , url = require('url')18 , utils = connect.utils;19 20 /**21+ * Expose `HTTPServer`.22+ */23+24+exports = module.exports = HTTPServer;25+26+/**27+ * Server proto.28+ */29+30+var app = HTTPServer.prototype;31+32+/**33 * Initialize a new `HTTPServer` with optional `middleware`.34 *35 * @param {Array} middleware36 * @api public37 */38 27-var Server = exports = module.exports = function HTTPServer(middleware){39+function HTTPServer(middleware){40 connect.HTTPServer.call(this, []);41 this.init(middleware);42 };43 44 /**45 * Inherit from `connect.HTTPServer`.46 */47 36-Server.prototype.__proto__ = connect.HTTPServer.prototype;48+app.__proto__ = connect.HTTPServer.prototype;49 50 /**51 * Initialize the server.52 *53 * @param {Array} middleware54 * @api private55 */56 45-Server.prototype.init = function(middleware){57+app.init = function(middleware){58 var self = this;59 this.cache = {};48- this.match = {};49- this.lookup = {};60 this.settings = {};61 this.redirects = {};62 this.isCallbacks = {};63 this._locals = {};64 this.dynamicViewHelpers = {};65 this.errorHandlers = [];66 57- // default "home" to /67 this.set('home', '/');59-60- // set "env" to NODE_ENV, defaulting to "development"68 this.set('env', process.env.NODE_ENV || 'development');69 70 // expose objects to each other71 this.use(function(req, res, next){41 unmodified lines113 // so that they disregard definition position.114 this.on('listening', this.registerErrorHandlers.bind(this));115 116 // route lookup methods117+ this.remove = function(url){118+ return self.remove.all(url);119+ };120+121+ this.match = function(url){122+ return self.match.all(url);123+ };124+125+ this.lookup = function(url){126+ return self.lookup.all(url);127+ };128+129 methods.forEach(function(method){130 self.match[method] = function(url){131 return self.router.match(url, 'all' == method132 ? null133 : method);134 };135 136+ self.remove[method] = function(url){137+ return self.router.remove(url, 'all' == method138+ ? null139+ : method);140+ };141+142 self.lookup[method] = function(path){143 return self.router.lookup(path, 'all' == method144 ? null145 : method);4 unmodified lines150 /**151 * When using the vhost() middleware register error handlers.152 */153 129-Server.prototype.onvhost = function(){154+app.onvhost = function(){155 this.registerErrorHandlers();156 };157 158 /**2 unmodified lines161 * @return {Server} for chaining162 * @api public163 */164 140-Server.prototype.registerErrorHandlers = function(){165+app.registerErrorHandlers = function(){166 this.errorHandlers.forEach(function(fn){167 this.use(function(err, req, res, next){168 fn.apply(this, arguments);169 });10 unmodified lines180 * @return {Server} for chaining181 * @api public182 */183 159-Server.prototype.use = function(route, middleware){184+app.use = function(route, middleware){185 var app, home, handle;186 187 if ('string' != typeof route) {188 middleware = route, route = '/';49 unmodified lines238 * @return {Server} for chaining239 * @api public240 */241 217-Server.prototype.mounted = function(fn){242+app.mounted = function(fn){243 this.__mounted = fn;244 return this;245 };246 3 unmodified lines250 * @return {Server} for chaining251 * @api public252 */253 229-Server.prototype.register = function(){254+app.register = function(){255 view.register.apply(this, arguments);256 return this;257 };258 5 unmodified lines264 * @return {Server} for chaining265 * @api public266 */267 243-Server.prototype.helpers =244-Server.prototype.locals = function(obj){268+app.helpers =269+app.locals = function(obj){270 utils.merge(this._locals, obj);271 return this;272 };273 5 unmodified lines279 * @return {Server} for chaining280 * @api public281 */282 258-Server.prototype.dynamicHelpers = function(obj){283+app.dynamicHelpers = function(obj){284 utils.merge(this.dynamicViewHelpers, obj);285 return this;286 };287 39 unmodified lines327 * @return {Server} for chaining328 * @api public329 */330 306-Server.prototype.param = function(name, fn){331+app.param = function(name, fn){332 if (Array.isArray(name)) {333 name.forEach(function(name){334 this.param(name, fn);335 }, this);12 unmodified lines348 * @return {Server} for chaining349 * @api public350 */351 327-Server.prototype.error = function(fn){352+app.error = function(fn){353 this.errorHandlers.push(fn);354 return this;355 };356 5 unmodified lines362 * @return {Server} for chaining363 * @api public364 */365 341-Server.prototype.is = function(type, fn){366+app.is = function(type, fn){367 if (!fn) return this.isCallbacks[type];368 this.isCallbacks[type] = fn;369 return this;370 };7 unmodified lines378 * @return {Server|Mixed} for chaining, or the setting value379 * @api public380 */381 357-Server.prototype.set = function(setting, val){382+app.set = function(setting, val){383 if (val === undefined) {384 if (this.settings.hasOwnProperty(setting)) {385 return this.settings[setting];386 } else if (this.parent) {12 unmodified lines399 * @return {Boolean}400 * @api public401 */402 378-Server.prototype.enabled = function(setting){403+app.enabled = function(setting){404 return !!this.set(setting);405 };406 407 /**3 unmodified lines411 * @return {Boolean}412 * @api public413 */414 390-Server.prototype.disabled = function(setting){415+app.disabled = function(setting){416 return !this.set(setting);417 };418 419 /**3 unmodified lines423 * @return {Server} for chaining424 * @api public425 */426 402-Server.prototype.enable = function(setting){427+app.enable = function(setting){428 return this.set(setting, true);429 };430 431 /**3 unmodified lines435 * @return {Server} for chaining436 * @api public437 */438 414-Server.prototype.disable = function(setting){439+app.disable = function(setting){440 return this.set(setting, false);441 };442 443 /**4 unmodified lines448 * @return {Server} for chaining449 * @api public450 */451 427-Server.prototype.redirect = function(key, url){452+app.redirect = function(key, url){453 this.redirects[key] = url;454 return this;455 };456 5 unmodified lines462 * @return {Server} for chaining463 * @api public464 */465 441-Server.prototype.configure = function(env, fn){466+app.configure = function(env, fn){467 if ('function' == typeof env) {468 fn = env, env = 'all';469 }470 if ('all' == env || env == this.settings.env) {4 unmodified lines475 476 // Generate routing methods477 478 function generateMethod(method){454- Server.prototype[method] = function(path){479+ app[method] = function(path){480 var self = this;481 482 // Lookup483 if (1 == arguments.length) {15 unmodified lines499 methods.forEach(generateMethod);500 501 // Alias delete as "del"502 478-Server.prototype.del = Server.prototype.delete;503+app.del = app.delete;modified:lib/https.js+15 added-3 removed
12 unmodified lines1314151617181920212223242526272829303132333435362537383940414243444534464748495039515212 unmodified lines , HTTPServer = require('./http') , https = require('https');
/** * Expose `HTTPSServer`. */
exports = module.exports = HTTPSServer;
/** * Server proto. */
var app = HTTPSServer.prototype;
/** * Initialize a new `HTTPSServer` with the * given `options`, and optional `middleware`. * * @param {Object} options * @param {Array} middleware * @api public */
var Server = exports = module.exports = function HTTPSServer(options, middleware){function HTTPSServer(options, middleware){ connect.HTTPSServer.call(this, options, []); this.init(middleware);};
/** * Inherit from `connect.HTTPSServer`. */
Server.prototype.__proto__ = connect.HTTPSServer.prototype;app.__proto__ = connect.HTTPSServer.prototype;
// mixin HTTPServer methods
Object.keys(HTTPServer.prototype).forEach(function(method){ Server.prototype[method] = HTTPServer.prototype[method]; app[method] = HTTPServer.prototype[method];});modified:test/express.test.js+3 added-185 removed
4 unmodified lines5 6 var express = require('express')7 , connect = require('connect')8 , assert = require('assert')9- , should = require('should');9+ , should = require('should')10+ , Route = express.Route;11 12 module.exports = {13 'test inheritance': function(){14 var server = express.createServer();2 unmodified lines17 18 'test constructor exports': function(){19 express.should.have.property('HTTPServer');20 express.should.have.property('HTTPSServer');21+ express.should.have.property('Route');22 },23 24 'test connect middleware autoloaders': function(){25 express.errorHandler.should.equal(connect.errorHandler);408 unmodified lines434 assert.response(app,435 { url: '/' },436 { body: 'restored' }437 );436- },437- 438- 'test route middleware': function(beforeExit){439- var app = express.createServer()440- , calls = 0;441-442- function allow(role) {443- return function(req, res, next) {444- // this is totally not real, dont use this :)445- // for tests only446- if (req.headers['x-role'] == role) {447- next();448- } else {449- res.send(401);450- }451- }452- }453- 454- function restrictAge(age) {455- return function(req, res, next){456- if (req.headers['x-age'] >= age) {457- next();458- } else {459- res.send(403);460- }461- }462- }463-464- app.param('user', function(req, res, next, user){465- ++calls;466- next();467- });468-469- app.get('/xxx', allow('member'), restrictAge(18), function(req, res){470- res.send(200);471- });472-473- app.get('/booze', [allow('member')], restrictAge(18), function(req, res){474- res.send(200);475- });476-477- app.get('/tobi', [allow('member')], [[restrictAge(18)]], function(req, res){478- res.send(200);479- });480- 481- app.get('/user/:user', [allow('member')], [[restrictAge(18)]], function(req, res){482- res.send(200);483- });484-485- ['xxx', 'booze', 'tobi', 'user/tj'].forEach(function(thing){486- assert.response(app,487- { url: '/' + thing },488- { body: 'Unauthorized', status: 401 });489- assert.response(app,490- { url: '/' + thing, headers: { 'X-Role': 'member' }},491- { body: 'Forbidden', status: 403 });492- assert.response(app,493- { url: '/' + thing, headers: { 'X-Role': 'member', 'X-Age': 18 }},494- { body: 'OK', status: 200 });495- });496-497- beforeExit(function(){498- calls.should.equal(3);499- });500- },501- 502- 'test named capture groups': function(){503- var app = express.createServer();504-505- app.get('/user/:id([0-9]{2,10})', function(req, res){506- res.send('user ' + req.params.id);507- });508-509- assert.response(app,510- { url: '/user/12' },511- { body: 'user 12' });512- 513- assert.response(app,514- { url: '/user/ab' },515- { body: 'Cannot GET /user/ab' });516- },517- 518- 'test .param()': function(){519- var app = express.createServer();520-521- var users = [522- { name: 'tj' }523- , { name: 'tobi' }524- , { name: 'loki' }525- , { name: 'jane' }526- , { name: 'bandit' }527- ];528-529- function integer(n){ return parseInt(n, 10); };530- app.param(['to', 'from'], integer);531-532- app.param('user', function(req, res, next, id){533- if (req.user = users[id]) {534- next();535- } else {536- next(new Error('failed to find user'));537- }538- });539-540- app.get('/user/:user', function(req, res, next){541- res.send('user ' + req.user.name);542- });543-544- app.get('/users/:from-:to', function(req, res, next){545- var names = users.slice(req.params.from, req.params.to).map(function(user){546- return user.name;547- });548- res.send('users ' + names.join(', '));549- });550- 551- assert.response(app,552- { url: '/user/0' },553- { body: 'user tj' });554- 555- assert.response(app,556- { url: '/user/1' },557- { body: 'user tobi' });558- 559- assert.response(app,560- { url: '/users/0-3' },561- { body: 'users tj, tobi, loki' });562- },563- 564- 'test OPTIONS': function(){565- var app = express.createServer();566- 567- app.get('/', function(){});568- app.get('/user/:id', function(){});569- app.put('/user/:id', function(){});570- 571- assert.response(app,572- { url: '/', method: 'OPTIONS' },573- { headers: { Allow: 'GET' }});574- 575- assert.response(app,576- { url: '/user/12', method: 'OPTIONS' },577- { headers: { Allow: 'GET,PUT' }});578- },579- 580- 'test app.lookup': function(){581- var app = express.createServer();582- app.get('/user', function(){});583- app.get('/user/:id', function(){});584- app.get('/user/:id/:op?', function(){});585- app.put('/user/:id', function(){});586- app.get('/user/:id/edit', function(){});587-588- app.get('/user').should.have.length(1);589- app.get('/user/:id').should.have.length(1);590- app.get('/user/:id/:op?').should.have.length(1);591- app.put('/user/:id').should.have.length(1);592- app.get('/user/:id/edit').should.have.length(1);593- app.get('/').should.have.be.empty;594- app.all('/user/:id').should.have.length(2);595- 596- app.lookup.get('/user').should.have.length(1);597- app.lookup.get('/user/:id').should.have.length(1);598- app.lookup.get('/user/:id/:op?').should.have.length(1);599- app.lookup.put('/user/:id').should.have.length(1);600- app.lookup.get('/user/:id/edit').should.have.length(1);601- app.lookup.get('/').should.have.be.empty;602- app.lookup.all('/user/:id').should.have.length(2);603- },604- 605- 'test app.match': function(){606- var app = express.createServer();607- app.get('/user', function(){});608- app.get('/user/:id', function(){});609- app.get('/user/:id/:op?', function(){});610- app.put('/user/:id', function(){});611- app.get('/user/:id/edit', function(){});612-613- app.match.get('/user').should.have.length(1);614- app.match.get('/user/12').should.have.length(2);615- app.match.get('/user/12/:op?').should.have.length(1);616- app.match.put('/user/100').should.have.length(1);617- app.match.get('/user/5/edit').should.have.length(2);618- app.match.get('/').should.have.be.empty;619- app.match.all('/user/123').should.have.length(3);438 }439 };added:test/router.test.js+245 added
1+2+/**3+ * Module dependencies.4+ */5+6+var express = require('express')7+ , connect = require('connect')8+ , assert = require('assert')9+ , should = require('should')10+ , Route = express.Route;11+12+module.exports = {13+ 'test route middleware': function(beforeExit){14+ var app = express.createServer()15+ , calls = 0;16+17+ function allow(role) {18+ return function(req, res, next) {19+ // this is totally not real, dont use this :)20+ // for tests only21+ if (req.headers['x-role'] == role) {22+ next();23+ } else {24+ res.send(401);25+ }26+ }27+ }28+ 29+ function restrictAge(age) {30+ return function(req, res, next){31+ if (req.headers['x-age'] >= age) {32+ next();33+ } else {34+ res.send(403);35+ }36+ }37+ }38+39+ app.param('user', function(req, res, next, user){40+ ++calls;41+ next();42+ });43+44+ app.get('/xxx', allow('member'), restrictAge(18), function(req, res){45+ res.send(200);46+ });47+48+ app.get('/booze', [allow('member')], restrictAge(18), function(req, res){49+ res.send(200);50+ });51+52+ app.get('/tobi', [allow('member')], [[restrictAge(18)]], function(req, res){53+ res.send(200);54+ });55+ 56+ app.get('/user/:user', [allow('member')], [[restrictAge(18)]], function(req, res){57+ res.send(200);58+ });59+60+ ['xxx', 'booze', 'tobi', 'user/tj'].forEach(function(thing){61+ assert.response(app,62+ { url: '/' + thing },63+ { body: 'Unauthorized', status: 401 });64+ assert.response(app,65+ { url: '/' + thing, headers: { 'X-Role': 'member' }},66+ { body: 'Forbidden', status: 403 });67+ assert.response(app,68+ { url: '/' + thing, headers: { 'X-Role': 'member', 'X-Age': 18 }},69+ { body: 'OK', status: 200 });70+ });71+72+ beforeExit(function(){73+ calls.should.equal(3);74+ });75+ },76+77+ 'test named capture groups': function(){78+ var app = express.createServer();79+80+ app.get('/user/:id([0-9]{2,10})', function(req, res){81+ res.send('user ' + req.params.id);82+ });83+84+ assert.response(app,85+ { url: '/user/12' },86+ { body: 'user 12' });87+ 88+ assert.response(app,89+ { url: '/user/ab' },90+ { body: 'Cannot GET /user/ab' });91+ },92+ 93+ 'test .param()': function(){94+ var app = express.createServer();95+96+ var users = [97+ { name: 'tj' }98+ , { name: 'tobi' }99+ , { name: 'loki' }100+ , { name: 'jane' }101+ , { name: 'bandit' }102+ ];103+104+ function integer(n){ return parseInt(n, 10); };105+ app.param(['to', 'from'], integer);106+107+ app.param('user', function(req, res, next, id){108+ if (req.user = users[id]) {109+ next();110+ } else {111+ next(new Error('failed to find user'));112+ }113+ });114+115+ app.get('/user/:user', function(req, res, next){116+ res.send('user ' + req.user.name);117+ });118+119+ app.get('/users/:from-:to', function(req, res, next){120+ var names = users.slice(req.params.from, req.params.to).map(function(user){121+ return user.name;122+ });123+ res.send('users ' + names.join(', '));124+ });125+ 126+ assert.response(app,127+ { url: '/user/0' },128+ { body: 'user tj' });129+ 130+ assert.response(app,131+ { url: '/user/1' },132+ { body: 'user tobi' });133+ 134+ assert.response(app,135+ { url: '/users/0-3' },136+ { body: 'users tj, tobi, loki' });137+ },138+ 139+ 'test OPTIONS': function(){140+ var app = express.createServer();141+ 142+ app.get('/', function(){});143+ app.get('/user/:id', function(){});144+ app.put('/user/:id', function(){});145+ 146+ assert.response(app,147+ { url: '/', method: 'OPTIONS' },148+ { headers: { Allow: 'GET' }});149+ 150+ assert.response(app,151+ { url: '/user/12', method: 'OPTIONS' },152+ { headers: { Allow: 'GET,PUT' }});153+ },154+ 155+ 'test app.lookup': function(){156+ var app = express.createServer();157+ app.get('/user', function(){});158+ app.get('/user/:id', function(){});159+ app.get('/user/:id/:op?', function(){});160+ app.put('/user/:id', function(){});161+ app.get('/user/:id/edit', function(){});162+163+ var route = app.get('/user/:id')[0]164+ route.should.be.an.instanceof(Route);165+ route.callback.should.be.a('function');166+ route.path.should.equal('/user/:id');167+ route.regexp.should.be.an.instanceof(RegExp);168+ route.method.should.equal('GET');169+ route.index.should.equal(1);170+ route.keys.should.eql(['id']);171+172+ app.get('/user').should.have.length(1);173+ app.get('/user/:id').should.have.length(1);174+ app.get('/user/:id/:op?').should.have.length(1);175+ app.put('/user/:id').should.have.length(1);176+ app.get('/user/:id/edit').should.have.length(1);177+ app.get('/').should.have.be.empty;178+ app.all('/user/:id').should.have.length(2);179+180+ app.lookup.get('/user').should.have.length(1);181+ app.lookup.get('/user/:id').should.have.length(1);182+ app.lookup.get('/user/:id/:op?').should.have.length(1);183+ app.lookup.put('/user/:id').should.have.length(1);184+ app.lookup.get('/user/:id/edit').should.have.length(1);185+ app.lookup.get('/').should.have.be.empty;186+ app.lookup.all('/user/:id').should.have.length(2);187+ app.lookup('/user/:id').should.have.length(2);188+ },189+190+ 'test app.remove': function(){191+ var app = express.createServer();192+ app.get('/user', function(){});193+ app.get('/user', function(){});194+ app.put('/user', function(){});195+196+ app.get('/user').should.have.length(2);197+ var removed = app.remove.get('/user');198+ removed.should.have.length(2);199+200+ var removed = app.remove.get('/user');201+ removed.should.have.length(0);202+ app.get('/user').should.have.length(0);203+204+ app.get('/user/:id', function(){});205+ app.put('/user/:id', function(){});206+ app.del('/user/:id', function(){});207+208+ app.remove.all('/user/:id').should.have.length(3);209+ app.remove.all('/user/:id').should.have.length(0);210+ 211+ app.get('/user/:id', function(){});212+ app.put('/user/:id', function(){});213+ app.del('/user/:id', function(){});214+215+ app.remove('/user/:id').should.have.length(3);216+ },217+ 218+ 'test app.match': function(){219+ var app = express.createServer();220+ app.get('/user', function(){});221+ app.get('/user/:id', function(){});222+ app.get('/user/:id/:op?', function(){});223+ app.put('/user/:id', function(){});224+ app.get('/user/:id/edit', function(){});225+226+ var route = app.match.get('/user/12')[0];227+ route.should.be.an.instanceof(Route);228+ route.callback.should.be.a('function');229+ route.path.should.equal('/user/:id');230+ route.regexp.should.be.an.instanceof(RegExp);231+ route.method.should.equal('GET');232+ route.index.should.equal(2);233+ route.keys.should.eql(['id']);234+ route.params.id.should.equal('12');235+236+ app.match.get('/user').should.have.length(1);237+ app.match.get('/user/12').should.have.length(2);238+ app.match.get('/user/12/:op?').should.have.length(1);239+ app.match.put('/user/100').should.have.length(1);240+ app.match.get('/user/5/edit').should.have.length(2);241+ app.match.get('/').should.have.be.empty;242+ app.match.all('/user/123').should.have.length(3);243+ app.match('/user/123').should.have.length(3);244+ }245+};