Skip to content
Myr

Refactored router. Closes #639

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 · parent 610fc92 · Browse files · 7 files+452 added−299 removed
This commit

State

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

Diff stats

7 files+452 added−299 removed

  • tests:+3 added−5 removed
  • other:+449 added−294 removed

7 files+452 added−299 removed

added:lib/router/collection.js+53 added
modified:lib/router/index.js+275 added-240 removed
12/*!3 * Express - router3 * Express - Router4 * Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>5 * MIT Licensed6 */78/**9 * Module dependencies.10 */1112var Route = require('./route')13 , Collection = require('./collection')12var utils = require('../utils')14 , utils = require('../utils')15 , parse = require('url').parse14 , _methods = require('./methods')15 , Route = require('./route');16 , toArray = utils.toArray;1718/**18 * Expose router.19 * Expose `Router` constructor.20 */2121exports = module.exports = router;22exports = module.exports = Router;2324/**24 * Expose methods.25 * Expose HTTP methods.26 */2727exports.methods = _methods;28var methods = exports.methods = require('./methods');2930/**30 * Provides Sinatra-like routing capabilities.31 * Initialize a new `Router` with the given `app`.32 * 33 * @param {express.HTTPServer} app34 * @api private35 */3637function Router(app) {38 var self = this;39 this.app = app;40 this.routes = {};41 this.params = {};42 this.middleware = function(req, res, next){43 self._dispatch(req, res, next);44 };45}4647/**48 * Register a param callback `fn` for the given `name`.49 *50 * @param {String} name51 * @param {Function} fn33 * @return {Function}34 * @api private52 * @return {Router} for chaining53 * @api public54 */5537function router(fn, app){38 var self = this39 , methods = {}40 , routes = {}41 , params = {};56Router.prototype.param = function(name, fn){57 this.params[name] = fn;58 return this;59};6043 if (!fn) throw new Error('router provider requires a callback function');61/**62 * Remove the given `route`, returns63 * a bool indicating if the route was present64 * or not.65 *66 * @param {Route} route67 * @return {Boolean}68 * @api public69 */7045 // Generate method functions46 _methods.forEach(function(method){47 methods[method] = generateMethodFunction(method.toUpperCase());48 });71Router.prototype.remove = function(route){72 var routes = this.routes[route.method]73 , len = routes.length;7450 // Alias del -> delete51 methods.del = methods.delete;75 for (var i = 0; i < len; ++i) {76 if (route == routes[i]) {77 routes.splice(i, 1);78 return true;79 }80 }81};8253 // Apply callback to all methods54 methods.all = function(){55 var args = arguments;56 _methods.forEach(function(name){57 methods[name].apply(this, args);58 });59 return self;60 };83/**84 * Return routes with route paths matching `path`.85 *86 * @param {String} method87 * @param {String} path88 * @return {Collection}89 * @api public90 */9162 // Register param callback63 methods.param = function(name, fn){64 params[name] = fn;65 };66 67 fn.call(this, methods);92Router.prototype.lookup = function(method, path){93 return this.find(function(route){94 return path == route.path95 && (route.method == method96 || method == 'all');97 });98};9969 function generateMethodFunction(name) {70 var localRoutes = routes[name] = routes[name] || [];71 return function(path, fn){72 var keys = []73 , middleware = [];100/**101 * Return routes with regexps that match the given `url`.102 *103 * @param {String} method104 * @param {String} url105 * @return {Collection}106 * @api public107 */10875 // slice middleware76 if (arguments.length > 2) {77 middleware = Array.prototype.slice.call(arguments, 1, arguments.length);78 fn = middleware.pop();79 middleware = utils.flatten(middleware);80 }109Router.prototype.match = function(method, url){110 return this.find(function(route){111 return route.match(url)112 && (route.method == method113 || method == 'all');114 });115};11682 if (!path) throw new Error(name + ' route requires a path');83 if (!fn) throw new Error(name + ' route ' + path + ' requires a callback');117/**118 * Find routes based on the return value of `fn`119 * which is invoked once per route.120 *121 * @param {Function} fn122 * @return {Collection}123 * @api public124 */12585 var options = { sensitive: app.enabled('case sensitive routes') };86 var route = new Route(name, path, fn, options);87 route.middleware = middleware;88 localRoutes.push(route);89 return self;90 };126Router.prototype.find = function(fn){127 var len = methods.length128 , ret = new Collection(this)129 , method130 , routes131 , route;132133 for (var i = 0; i < len; ++i) {134 method = methods[i];135 routes = this.routes[method];136 if (!routes) continue;137 for (var j = 0, jlen = routes.length; j < jlen; ++j) {138 route = routes[j];139 if (fn(route)) ret.push(route);140 }141 }14293 function router(req, res, next){143 return ret;144};145146/**147 * Route dispatcher aka the route "middleware".148 *149 * @param {IncomingMessage} req150 * @param {ServerResponse} res151 * @param {Function} next152 * @api private153 */154155Router.prototype._dispatch = function(req, res, next){156 var params = this.params157 , self = this;158159 // route dispatch160 (function pass(i){161 var route95 , self = this;162 , keys163 , ret;16497 (function pass(i){98 if (route = match(req, routes, i)) {99 var i = 0100 , keys = route.keys101 , ret;165 // match route166 route = self._match(req, i);167103 req.params = route.params;168 // implied OPTIONS169 if ('OPTIONS' == req.method) return self._options(req, res);170105 // Param preconditions106 (function param(err) {107 try {108 var key = keys[i++]109 , val = req.params[key]110 , fn = params[key];171 // no route172 if (!route) return next();173112 if ('route' == err) {113 pass(req._route_index + 1);114 // Error115 } else if (err) {116 next(err);117 // Param has callback118 } else if (fn) {119 // Return style120 if (fn.length < 3) {121 ret = req.params[key] = fn(val);122 if (invalidParam(ret)) {123 pass(req._route_index + 1);124 return;125 }126 param();127 // Middleware style128 } else {129 fn(req, res, param, val);130 }131 // Finished processing params132 } else if (!key) {133 // route middleware134 i = 0;135 (function nextMiddleware(err){136 var fn = route.middleware[i++];137 if ('route' == err) {138 pass(req._route_index + 1);139 } else if (err) {140 next(err);141 } else if (fn) {142 fn(req, res, nextMiddleware);143 } else {144 route.callback.call(self, req, res, function(err){145 if (err) {146 next(err);147 } else {148 pass(req._route_index + 1);149 }150 });151 }152 })();153 // More params154 } else {155 param();156 }157 } catch (err) {158 next(err);159 }160 })();161 } else if ('OPTIONS' == req.method) {162 options(req, res, routes);163 } else {164 next();165 }166 })();167 };174 // we have a route175 // start at param 0176 req.params = route.params;177 keys = route.keys;178 i = 0;179169 router.remove = function(path, method, ret){170 var ret = ret || []171 , route;180 (function param(err) {181 var key = keys[i++]182 , val = req.params[key]183 , fn = params[key]184 , ret;185173 // method specific remove174 if (method) {175 method = method.toUpperCase();176 if (routes[method]) {177 for (var i = 0; i < routes[method].length; ++i) {178 route = routes[method][i];179 if (path == route.path) {180 route.index = i;181 routes[method].splice(i, 1);182 ret.push(route);183 --i;186 try {187 if ('route' == err) {188 pass(req._route_index + 1);189 } else if (err) {190 next(err);191 } else if (fn && fn.length < 3) {192 ret = req.params[key] = fn(val);193 if (invalidParamReturnValue(ret)) {194 pass(req._route_index + 1);195 } else {196 param();197 }198 } else if (fn) {199 fn(req, res, param, val);200 } else if (key) {201 param();202 } else {203 i = 0;204 middleware();205 }206 } catch (err) {207 next(err);208 }187 // global remove188 } else {189 _methods.forEach(function(method){190 router.remove(path, method, ret);191 });209 })();192 }210194 return ret;195 };196197 router.lookup = function(path, method, ret){198 ret = ret || [];199200 // method specific lookup201 if (method) {202 method = method.toUpperCase();203 if (routes[method]) {204 routes[method].forEach(function(route, i){205 if (path == route.path) {206 route.index = i;207 ret.push(route);208 }209 });211 // invoke route middleware212 function middleware(err) {213 var fn = route.middleware[i++];214 if ('route' == err) {215 pass(req._route_index + 1);216 } else if (err) {217 next(err);218 } else if (fn) {219 fn(req, res, middleware);220 } else {221 done();222 }211 // global lookup212 } else {213 _methods.forEach(function(method){214 router.lookup(path, method, ret);215 });223 };216 }224218 return ret;219 };220221 router.match = function(url, method, ret){222 var ret = ret || []223 , i = 0224 , route225 , req;226227 // method specific matches228 if (method) {229 method = method.toUpperCase();230 req = { url: url, method: method };231 while (route = match(req, routes, i)) {232 i = req._route_index + 1;233 route.index = i;234 ret.push(route);235 } 236 // global matches237 } else {238 _methods.forEach(function(method){239 router.match(url, method, ret);225 // invoke middleware callback226 function done() {227 route.callback.call(self, req, res, function(err){228 if (err) return next(err);229 pass(req._route_index + 1);230 });231 }232 })(0);233};234243 return ret;244 };245246 router.routes = routes;247248 return router;249}250235/**252 * Respond to OPTIONS.236 * Respond to __OPTIONS__ method.237 *254 * @param {ServerRequest} req255 * @param {ServerResponse} req256 * @param {Array} routes238 * @param {IncomingMessage} req239 * @param {ServerResponse} res240 * @api private241 */242260function options(req, res, routes) {261 var pathname = parse(req.url).pathname262 , body = optionsFor(pathname, routes).join(',');243Router.prototype._options = function(req, res){244 var path = parse(req.url).pathname245 , body = this._optionsFor(path).join(',');246 res.send(body, { Allow: body });264}247};248249/**267 * Return OPTIONS array for the given `path`, matching `routes`.250 * Return an array of HTTP verbs or "options" for `path`.251 *252 * @param {String} path270 * @param {Array} routes253 * @return {Array}254 * @api private255 */256275function optionsFor(path, routes) {276 return _methods.filter(function(method){277 var arr = routes[method.toUpperCase()];278 for (var i = 0, len = arr.length; i < len; ++i) {279 if (arr[i].regexp.test(path)) return true;257Router.prototype._optionsFor = function(path){258 var self = this;259 return methods.filter(function(method){260 var routes = self.routes[method];261 if (!routes) return;262 for (var i = 0, len = routes.length; i < len; ++i) {263 if (routes[i].match(path)) return true;264 }265 }).map(function(method){266 return method.toUpperCase();267 });284}268};269270/**287 * Attempt to match the given request to288 * one of the routes. When successful289 * a route function is returned.271 * Attempt to match a route for `req`272 * starting from offset `i`.273 *291 * @param {ServerRequest} req292 * @param {Object} routes293 * @return {Function}274 * @param {IncomingMessage} req275 * @param {Number} i276 * @return {Route}277 * @api private278 */279297function match(req, routes, i) {298 var captures299 , method = req.method300 , i = i || 0;280Router.prototype._match = function(req, i){281 var method = req.method.toLowerCase()282 , url = parse(req.url)283 , path = url.pathname284 , routes = this.routes285 , captures286 , route287 , keys;288289 // pass HEAD to GET routes303 if ('HEAD' == method) method = 'GET';290 if ('head' == method) method = 'get';291292 // routes for this method293 if (routes = routes[method]) {307 var url = parse(req.url)308 , pathname = url.pathname;294295 // matching routes296 for (var len = routes.length; i < len; ++i) {312 var route = routes[i]313 , fn = route.callback314 , path = route.regexp315 , keys = route.keys;316317 // match318 if (captures = path.exec(pathname)) {297 route = routes[i];298 if (captures = route.match(path)) {299 keys = route.keys;300 route.params = [];320 for (var j = 1, l = captures.length; j < l; ++j) {301302 // params from capture groups303 for (var j = 1, jlen = captures.length; j < jlen; ++j) {304 var key = keys[j-1],305 val = 'string' == typeof captures[j]306 ? decodeURIComponent(captures[j])307 : captures[j];
2 unmodified lines
310 } else {311 route.params.push(val);312 }313 }314315 // all done316 req._route_index = i;317 return route;318 }319 }320 }336}321};322323/**324 * Route `method`, `path`, and optional middleware325 * to the callback `fn`.326 *327 * @param {String} method328 * @param {String} path329 * @param {Function} ...330 * @param {Function} fn331 * @return {Router} for chaining332 * @api private333 */334335Router.prototype._route = function(method, path, fn){336 var app = this.app337 , middleware = [];338339 // slice middleware340 if (arguments.length > 3) {341 middleware = toArray(arguments, 2);342 fn = middleware.pop();343 middleware = utils.flatten(middleware);344 }345346 // ensure path and callback are given347 if (!path) throw new Error(method + 'route requires a path');348 if (!fn) throw new Error(method + ' route ' + path + ' requires a callback');349350 // create the route351 var route = new Route(method, path, fn, {352 sensitive: app.enabled('case sensitive routes')353 , middleware: middleware354 });355356 // add it357 (this.routes[method] = this.routes[method] || [])358 .push(route);359 return this;360};361362/**363 * Check if `val` is an invalid return value, aka:364 *365 * - is `null` or `undefined`366 * - is `false`367 * - is `NaN`368 *369 * @param {Mixed} val370 * @return {Boolean}371 * @api private372 */373338function invalidParam(val) {374function invalidParamReturnValue(val){375 return null == val376 || false === val341 || ('number' == typeof val && isNaN(val))342 ;343}377 || ('number' == typeof val && isNaN(val));378};
modified:lib/router/route.js+15 added-1 removed
modified:lib/http.js+87 added-52 removed
10 unmodified lines
1112var qs = require('qs')13 , connect = require('connect')14 , router = require('./router')15 , methods = router.methods.concat('del', 'all')15 , Router = require('./router')16 , view = require('./view')17 , toArray = require('./utils').toArray18 , methods = router.methods.concat('del', 'all')19 , url = require('url')20 , utils = connect.utils;2122/**
64 unmodified lines
8788 // apply middleware89 if (middleware) middleware.forEach(self.use.bind(self));9089 // use router, expose as app.get(), etc90 var fn = router(function(app){ self.routes = app; }, this);91 // router92 this.routes = new Router(this);93 this.__defineGetter__('router', function(){94 this.__usedRouter = true;93 return fn;95 return self.routes.middleware;96 });9798 // default locals99 this.locals({
14 unmodified lines
114 // register error handlers on "listening"115 // so that they disregard definition position.116 this.on('listening', this.registerErrorHandlers.bind(this));117116 // route lookup methods117 this.remove = function(url){118 return self.remove.all(url);119 };120121 this.match = function(url){122 return self.match.all(url);123 };124125 this.lookup = function(url){126 return self.lookup.all(url);127 };128118 // route manipulation methods119 methods.forEach(function(method){130 self.match[method] = function(url){131 return self.router.match(url, 'all' == method132 ? null133 : method);120 self.lookup[method] = function(path){121 return self.routes.lookup(method, path);122 };123136 self.remove[method] = function(url){137 return self.router.remove(url, 'all' == method138 ? null139 : method);124 self.match[method] = function(path){125 return self.routes.match(method, path);126 };127142 self.lookup[method] = function(path){143 return self.router.lookup(path, 'all' == method144 ? null145 : method);128 self.remove[method] = function(path){129 return self.routes.lookup(method, path).remove();130 };131 });132133 // del -> delete134 self.lookup.del = self.lookup.delete;135 self.match.del = self.match.delete;136 self.remove.del = self.remove.delete;137};138139/**140 * Remove routes matching the given `path`.141 *142 * @param {Route} path143 * @return {Boolean}144 * @api public145 */146147app.remove = function(path){148 return this.routes.lookup('all', path).remove();149};150151/**152 * Lookup routes defined with a path153 * equivalent to `path`.154 *155 * @param {Stirng} path156 * @return {Array}157 * @api public158 */159160app.lookup = function(path){161 return this.routes.lookup('all', path);162};163164/**165 * Lookup routes matching the given `url`.166 *167 * @param {Stirng} url168 * @return {Array}169 * @api public170 */171172app.match = function(url){173 return this.routes.match('all', url);174};175176/**177 * When using the vhost() middleware register error handlers.178 */179180app.onvhost = function(){
308 unmodified lines
489 * @api public490 */491492app.configure = function(env, fn){467 if ('function' == typeof env) {468 fn = env, env = 'all';469 }470 if ('all' == env || env == this.settings.env) {471 fn.call(this);472 }493 if ('function' == typeof env) fn = env, env = 'all';494 if ('all' == env || env == this.settings.env) fn.call(this);495 return this;496};497476// Generate routing methods498/**499 * Delegate `.VERB(...)` calls to `.route(VERB, ...)`.500 */501502methods.forEach(function(method){503 app[method] = function(path){480 var self = this;481482 // Lookup483 if (1 == arguments.length) {484 return this.router.lookup(path, 'all' == method485 ? null486 : method);487 }488489 // Ensure router is mounted504 if (1 == arguments.length) return this.routes.lookup(method, path);505 var args = [method].concat(toArray(arguments));506 if (!this.__usedRouter) this.use(this.router);491492 // Generate the route493 this.routes[method].apply(this, arguments);494 return this;495 };507 return this.routes._route.apply(this.routes, args);508 }509});510498// Alias delete as "del"511/**512 * Special-cased "all" method, applying the given route `path`,513 * middleware, and callback to _every_ HTTP method.514 *515 * @param {String} path516 * @param {Function} ...517 * @return {Server} for chaining518 * @api public519 */520521app.all = function(path){522 var args = arguments;523 if (1 == args.length) return this.routes.lookup('all', path);524 methods.forEach(function(method){525 if ('all' == method) return;526 app[method].apply(this, args);527 }, this);528 return this;529};530531// del -> delete alias532533app.del = app.delete;534535
modified:lib/utils.js+17 added
118 unmodified lines
119 return { start: start, end: end };120 });121 return valid ? arr : undefined;122};123124/**125 * Fast alternative to `Array.prototype.slice.call()`.126 *127 * @param {Arguments} args128 * @param {Number} n129 * @return {Array}130 * @api public131 */132133exports.toArray = function(args, i){134 var arr = []135 , len = args.length136 , i = i || 0;137 for (; i < len; ++i) arr.push(args[i]);138 return arr;139};
modified:test/router.test.js+3 added-5 removed
214 unmodified lines
215 route.should.be.an.instanceof(Route);216 route.callback.should.be.a('function');217 route.path.should.equal('/user/:id');218 route.regexp.should.be.an.instanceof(RegExp);219 route.method.should.equal('GET');220 route.index.should.equal(1);219 route.method.should.equal('get');220 route.keys.should.eql(['id']);221222 app.get('/user').should.have.length(1);223 app.get('/user/:id').should.have.length(1);
53 unmodified lines
277 route.should.be.an.instanceof(Route);278 route.callback.should.be.a('function');279 route.path.should.equal('/user/:id');280 route.regexp.should.be.an.instanceof(RegExp);282 route.method.should.equal('GET');283 route.index.should.equal(2);281 route.method.should.equal('get');282 route.keys.should.eql(['id']);285 route.params.id.should.equal('12');283 //route.params.id.should.equal('12');284285 app.match.get('/user').should.have.length(1);286 app.match.get('/user/12').should.have.length(2);287 app.match.get('/user/12/:op?').should.have.length(1);
29 unmodified lines
modified:Makefile+2 added-1 removed
12DOCS = $(shell find docs/*.md)3HTMLDOCS =$(DOCS:.md=.html)4TESTS = $(shell find test/*.test.js)56test:7 @NODE_ENV=test ./node_modules/.bin/expresso \8 -I lib \9 $(TESTFLAGS) \9 test/*.test.js10 $(TESTS)1112test-cov:13 @TESTFLAGS=--cov $(MAKE) test14
21 unmodified lines