Skip to content
Myr

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

6 files+167 added−107 removed

modified:lib/router/index.js+65 added-38 removed
1 unmodified line
2 * Module dependencies.3 */45var 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 lines
162 try {163 var path = parseUrl(req).pathname;164 if (undefined == path) path = '/';165166 if (!layer.match(path)) return next(err);167168 // route object and not middleware169 var route = layer.route;170168 // 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 }177175 req.params = route.params;178 req.route = route;179180 // we can now dispatch to the route181 if (method === 'options' && !route.methods['options']) {182 options.push.apply(options, route._options());183 }184 }185182 return self.process_params(route, req, res, function(err) {183 if (err) {184 return next(err);185 }186 req.params = layer.params;187187 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 }193191 // 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 }197194 var c = path[layer.path.length];195 if (c && '/' != c && '.' != c) return next(err);198 trim_prefix();199 });200197 // 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);202203 // 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);206207 // 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);212213 // Ensure leading slash214 if (!fqdn && '/' != req.url[0]) {215 req.url = '/' + req.url;216 slashAdded = true;217 }218209 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 lines
248249 // captured parameters from the route, keys and values250 var keys = route.keys || [];251252 // fast track253 if (keys.length === 0) {254 return done();255 }256257 var i = 0;258 var paramIndex = 0;259 var key;260 var paramVal;
68 unmodified lines
329 if ('/' == route[route.length - 1]) {330 route = route.slice(0, -1);331 }332333 var layer = Layer(route, {334 sensitive: this.caseSensitive,335 strict: this.strict,336 end: false337 }, fn);338339 // add the middleware340 debug('use %s %s', route || '/', fn.name || 'anonymous');319 this.stack.push({ path: route, handle: fn });341342 this.stack.push(layer);343 return this;344};345346/**
9 unmodified lines
356 * @api public357 */358359Router.prototype.route = function(path){338 var route = new Route(path, {360 var route = new Route(path);361362 var layer = Layer(path, {363 sensitive: this.caseSensitive,340 strict: this.strict341 });364 strict: this.strict,365 end: true366 }, route.dispatch.bind(route));367343 this.stack.push({ path: path, route: route });368 layer.route = route;369370 this.stack.push(layer);371 return route;372};373374/**
24 unmodified lines
added:lib/router/layer.js+61 added
modified:lib/router/route.js+3 added-58 removed
1 unmodified line
2/**3 * Module dependencies.4 */56var utils = require('../utils')7 , debug = require('debug')('express:router:route')6var debug = require('debug')('express:router:route')7 , methods = require('methods')89/**10 * Expose `Route`.
1 unmodified line
1213module.exports = Route;1415/**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 */2130function Route(path, options) {22function 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);3925 this.stack = undefined;2627 // route handlers for various http methods28 this.methods = {};29}3031/**47 * Check if this route matches `path`, if so48 * populate `.params`.49 *50 * @param {String} path51 * @return {Boolean}52 * @api private53 */5455Route.prototype.match = function(path){56 var keys = this.keys57 , params = this.params = {}58 , m = this.regexp.exec(path)59 , n = 0;6061 if (!m) return false;6263 for (var i = 1, len = m.length; i < len; ++i) {64 var key = keys[i - 1];6566 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 }7576 if (key) {77 params[key.name] = val;78 } else {79 params[n++] = val;80 }81 }8283 return true;84};8586/**32 * @return {Array} supported HTTP methods33 * @api private34 */35
129 unmodified lines
modified:lib/utils.js+3 added-2 removed
130 unmodified lines
131 * @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 */139139exports.pathRegexp = function(path, keys, sensitive, strict) {140exports.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 lines
155 + (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}161162/**163 * Parse the `req` url with memoization.
21 unmodified lines
modified:test/Route.js-9 removed
modified:test/Router.js+35 added
92 unmodified lines
93 assert.equal(count, methods.length);94 done();95 })96 })9798 describe('.param', function() {99 it('should call param function when routing VERBS', function(done) {100 var router = new Router();101102 router.param('id', function(req, res, next, id) {103 assert.equal(id, '123');104 next();105 });106107 router.get('/foo/:id/bar', function(req, res, next) {108 assert.equal(req.params.id, '123');109 next();110 });111112 router.handle({ url: '/foo/123/bar', method: 'get' }, {}, done);113 });114115 it('should call param function when routing middleware', function(done) {116 var router = new Router();117118 router.param('id', function(req, res, next, id) {119 assert.equal(id, '123');120 next();121 });122123 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 });128129 router.handle({ url: '/foo/123/bar/baz', method: 'get' }, {}, done);130 });131 });132})