Merge pull request #1935 from visionmedia/router-params-middleware
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Roman Shtylman · committed by Roman Shtylman · parents 0719e5f, 6911815 · Browse files · 6 files·+167 added−107 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- Router: add parameter handling to middleware
Diff stats
6 files+167 added−107 removed
- tests:+35 added−9 removed
- other:+132 added−98 removed
Provenance
- Commit
caa25b5- Tree
f5e45e5- Author
Roman Shtylman <shtylman@gmail.com>- Committer
Roman Shtylman <shtylman@gmail.com>- Parent 1
0719e5f- Parent 2
6911815
6 files changed+167 added−107 removed
modified:lib/router/index.js+65 added-38 removed
1 unmodified line2 * Module dependencies.3 */4 5 var Route = require('./route')6+ , Layer = require('./layer')7 , utils = require('../utils')8 , methods = require('methods')9 , debug = require('debug')('express:router')10 , parseUrl = utils.parseUrl;151 unmodified lines162 try {163 var path = parseUrl(req).pathname;164 if (undefined == path) path = '/';165 166+ if (!layer.match(path)) return next(err);167+168 // route object and not middleware169 var route = layer.route;170 168- // handle route171+ // if final route, then we support options172 if (route) {173 // we don't run any routs with error first171- if (err || !route.match(path)) {174+ if (err) {175 return next(err);176 }177 175- req.params = route.params;178+ req.route = route;179 180 // we can now dispatch to the route181 if (method === 'options' && !route.methods['options']) {182 options.push.apply(options, route._options());183 }184+ }185 182- return self.process_params(route, req, res, function(err) {183- if (err) {184- return next(err);185- }186+ req.params = layer.params;187 187- route.dispatch(req, res, next);188- });189- }188+ // this should be done for the layer189+ return self.process_params(layer, req, res, function(err) {190+ if (err) {191+ return next(err);192+ }193 191- // skip this layer if the path doesn't match.192- if (0 != path.toLowerCase().indexOf(layer.path.toLowerCase())) return next(err);194+ if (route) {195+ return layer.handle(req, res, next);196+ }197 194- var c = path[layer.path.length];195- if (c && '/' != c && '.' != c) return next(err);198+ trim_prefix();199+ });200 197- // Trim off the part of the url that matches the route198- // middleware (.use stuff) needs to have the path stripped199- debug('trim prefix (%s) from url %s', removed, req.url);200- removed = layer.path;201- req.url = protohost + req.url.substr(protohost.length + removed.length);201+ return next(err);202 203- // Ensure leading slash204- if (!fqdn && '/' != req.url[0]) {205- req.url = '/' + req.url;206- slashAdded = true;207- }203+ function trim_prefix() {204+ var c = path[layer.path.length];205+ if (c && '/' != c && '.' != c) return next(err);206 207+ // Trim off the part of the url that matches the route208+ // middleware (.use stuff) needs to have the path stripped209+ debug('trim prefix (%s) from url %s', removed, req.url);210+ removed = layer.path;211+ req.url = protohost + req.url.substr(protohost.length + removed.length);212+213+ // Ensure leading slash214+ if (!fqdn && '/' != req.url[0]) {215+ req.url = '/' + req.url;216+ slashAdded = true;217+ }218+209- debug('%s %s : %s', layer.handle.name || 'anonymous', layer.path, req.originalUrl);210- var arity = layer.handle.length;211- if (err) {212- if (arity === 4) {213- layer.handle(err, req, res, next);219+ debug('%s %s : %s', layer.handle.name || 'anonymous', layer.path, req.originalUrl);220+ var arity = layer.handle.length;221+ if (err) {222+ if (arity === 4) {223+ layer.handle(err, req, res, next);224+ } else {225+ next(err);226+ }227+ } else if (arity < 4) {228+ layer.handle(req, res, next);229 } else {230 next(err);231 }217- } else if (arity < 4) {218- layer.handle(req, res, next);219- } else {220- next(err);232 }233 } catch (err) {234 next(err);235 }12 unmodified lines248 249 // captured parameters from the route, keys and values250 var keys = route.keys || [];251 252+ // fast track253+ if (keys.length === 0) {254+ return done();255+ }256+257 var i = 0;258 var paramIndex = 0;259 var key;260 var paramVal;68 unmodified lines329 if ('/' == route[route.length - 1]) {330 route = route.slice(0, -1);331 }332 333+ var layer = Layer(route, {334+ sensitive: this.caseSensitive,335+ strict: this.strict,336+ end: false337+ }, fn);338+339 // add the middleware340 debug('use %s %s', route || '/', fn.name || 'anonymous');319- this.stack.push({ path: route, handle: fn });341 342+ this.stack.push(layer);343 return this;344 };345 346 /**9 unmodified lines356 * @api public357 */358 359 Router.prototype.route = function(path){338- var route = new Route(path, {360+ var route = new Route(path);361+362+ var layer = Layer(path, {363 sensitive: this.caseSensitive,340- strict: this.strict341- });364+ strict: this.strict,365+ end: true366+ }, route.dispatch.bind(route));367 343- this.stack.push({ path: path, route: route });368+ layer.route = route;369+370+ this.stack.push(layer);371 return route;372 };373 374 /**24 unmodified linesadded:lib/router/layer.js+61 added
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061var utils = require('../utils') , debug = require('debug')('express:router:layer')
function Layer(path, options, fn) { if (!(this instanceof Layer)) { return new Layer(path, options, fn); }
debug('new %s', path); options = options || {}; this.path = path; this.params = {}; this.regexp = utils.pathRegexp(path , this.keys = [] , options.sensitive , options.strict , options.end); this.handle = fn;}
/** * Check if this route matches `path`, if so * populate `.params`. * * @param {String} path * @return {Boolean} * @api private */
Layer.prototype.match = function(path){ var keys = this.keys , params = this.params = {} , m = this.regexp.exec(path) , n = 0;
if (!m) return false;
for (var i = 1, len = m.length; i < len; ++i) { var key = keys[i - 1];
try { var val = 'string' == typeof m[i] ? decodeURIComponent(m[i]) : m[i]; } catch(e) { var err = new Error("Failed to decode param '" + m[i] + "'"); err.status = 400; throw err; }
if (key) { params[key.name] = val; } else { params[n++] = val; } }
return true;};
module.exports = Layer;modified:lib/router/route.js+3 added-58 removed
1 unmodified line2 /**3 * Module dependencies.4 */5 6-var utils = require('../utils')7- , debug = require('debug')('express:router:route')6+var debug = require('debug')('express:router:route')7 , methods = require('methods')8 9 /**10 * Expose `Route`.1 unmodified line12 13 module.exports = Route;14 15 /**17- * Initialize `Route` with the given HTTP `method`, `path`,18- * and an array of `callbacks` and `options`.16+ * Initialize `Route` with the given `path`,17 *20- * Options:21- *22- * - `sensitive` enable case-sensitive routes23- * - `strict` enable strict matching for trailing slashes24- *18 * @param {String} path26- * @param {Object} options.19 * @api private20 */21 30-function Route(path, options) {22+function Route(path) {23 debug('new %s', path);32- options = options || {};24 this.path = path;34- this.params = {};35- this.regexp = utils.pathRegexp(path36- , this.keys = []37- , options.sensitive38- , options.strict);39-25 this.stack = undefined;26 27 // route handlers for various http methods28 this.methods = {};29 }30 31 /**47- * Check if this route matches `path`, if so48- * populate `.params`.49- *50- * @param {String} path51- * @return {Boolean}52- * @api private53- */54-55-Route.prototype.match = function(path){56- var keys = this.keys57- , params = this.params = {}58- , m = this.regexp.exec(path)59- , n = 0;60-61- if (!m) return false;62-63- for (var i = 1, len = m.length; i < len; ++i) {64- var key = keys[i - 1];65-66- try {67- var val = 'string' == typeof m[i]68- ? decodeURIComponent(m[i])69- : m[i];70- } catch(e) {71- var err = new Error("Failed to decode param '" + m[i] + "'");72- err.status = 400;73- throw err;74- }75-76- if (key) {77- params[key.name] = val;78- } else {79- params[n++] = val;80- }81- }82-83- return true;84-};85-86-/**32 * @return {Array} supported HTTP methods33 * @api private34 */35 129 unmodified linesmodified:lib/utils.js+3 added-2 removed
130 unmodified lines131 * @param {String|RegExp|Array} path132 * @param {Array} keys133 * @param {Boolean} sensitive134 * @param {Boolean} strict135+ * @param {Boolean} end (whether to append $ to regex)136 * @return {RegExp}137 * @api private138 */139 139-exports.pathRegexp = function(path, keys, sensitive, strict) {140+exports.pathRegexp = function(path, keys, sensitive, strict, end) {141 if (toString.call(path) == '[object RegExp]') return path;142 if (Array.isArray(path)) path = '(' + path.join('|') + ')';143 path = path144 .concat(strict ? '' : '/?')10 unmodified lines155 + (star ? '(/*)?' : '');156 })157 .replace(/([\/.])/g, '\\$1')158 .replace(/\*/g, '(.*)');158- return new RegExp('^' + path + '$', sensitive ? '' : 'i');159+ return new RegExp('^' + path + ((end) ? '$' : ''), sensitive ? '' : 'i');160 }161 162 /**163 * Parse the `req` url with memoization.21 unmodified linesmodified:test/Route.js-9 removed
4 unmodified lines5678910111213141516179101112132 unmodified linesExpand all4 unmodified lines , assert = require('assert');
describe('Route', function(){
describe('.match', function(){ it('should match', function(){ var route = new Route('/foo/bar');
assert(route.match('/foo/bar')); assert(!route.match('/foo/baz')); }) })
describe('.all', function(){ it('should add handler', function(done){ var route = new Route('/foo');
132 unmodified linesExpand allmodified:test/Router.js+35 added
92 unmodified lines93 assert.equal(count, methods.length);94 done();95 })96 })97+98+ describe('.param', function() {99+ it('should call param function when routing VERBS', function(done) {100+ var router = new Router();101+102+ router.param('id', function(req, res, next, id) {103+ assert.equal(id, '123');104+ next();105+ });106+107+ router.get('/foo/:id/bar', function(req, res, next) {108+ assert.equal(req.params.id, '123');109+ next();110+ });111+112+ router.handle({ url: '/foo/123/bar', method: 'get' }, {}, done);113+ });114+115+ it('should call param function when routing middleware', function(done) {116+ var router = new Router();117+118+ router.param('id', function(req, res, next, id) {119+ assert.equal(id, '123');120+ next();121+ });122+123+ router.use('/foo/:id/bar', function(req, res, next) {124+ assert.equal(req.params.id, '123');125+ assert.equal(req.url, '/baz');126+ next();127+ });128+129+ router.handle({ url: '/foo/123/bar/baz', method: 'get' }, {}, done);130+ });131+ });132 })