Store matched routes in request by gabegorelick · Pull Request #86 · pillarjs/router

Expand Up @@ -14,6 +14,7 @@
var pathRegexp = require('path-to-regexp') var debug = require('debug')('router:layer') var flatten = require('array-flatten')
/** * Module variables. Expand All @@ -28,23 +29,48 @@ var hasOwnProperty = Object.prototype.hasOwnProperty
module.exports = Layer
function Layer(path, options, fn) { function Layer(p, options, fn) { if (!(this instanceof Layer)) { return new Layer(path, options, fn) return new Layer(p, options, fn) }
debug('new %o', path) debug('new %o', paths) var opts = options || {}
// If not in strict allow both with or without trailing slash var paths = p if (!opts.strict) { if (!Array.isArray(paths) && paths !== '/' && paths[paths.length - 1] === '/') { paths = paths.substr(0, paths.length - 1) } else { for (var i = 0; i < paths.length; i++) { if (paths[i] !== '/' && paths[i][paths[i].length - 1] === '/') { paths[i] = paths[i].substr(0, paths[i].length - 1) } } } }
this.handle = fn this.name = fn.name || '<anonymous>' this.params = undefined this.path = undefined this.regexp = pathRegexp(path, this.keys = [], opts) this.matchedPath = undefined
// set fast path flags this.regexp.fast_star = path === '*' this.regexp.fast_slash = path === '/' && opts.end === false this.fastStar = paths === '*' this.fastSlash = paths === '/' && opts.end === false
this.paths = (!Array.isArray(paths) ? [paths] : flatten(paths)).map(function (path) { var keys = [] var pathObj = { path: path, keys: keys, regexp: pathRegexp(path, keys, opts) }
return pathObj }) }
/** Expand Down Expand Up @@ -123,29 +149,39 @@ Layer.prototype.handle_request = function handle(req, res, next) {
Layer.prototype.match = function match(path) { var match var checkPath
if (path != null) { // fast path non-ending match for / (any path matches) if (this.regexp.fast_slash) { if (this.fastSlash) { this.params = {} this.path = '' this.matchedPath = this.paths[0] return true }
// fast path for * (everything matched in a param) if (this.regexp.fast_star) { if (this.fastStar) { this.params = {'0': decode_param(path)} this.path = path this.matchedPath = this.paths[0] return true }
// match the path match = this.regexp.exec(path) for (var i = 0; i < this.paths.length; i++) { checkPath = this.paths[i] if (match = checkPath.regexp.exec(path)) { this.matchedPath = checkPath break } } }
if (!match) { this.params = undefined this.path = undefined this.matchedPath = undefined return false }
Expand All @@ -158,7 +194,7 @@ Layer.prototype.match = function match(path) { var params = this.params
for (var i = 1; i < match.length; i++) { var key = keys[i - 1] var key = this.matchedPath.keys[i - 1] var prop = key.name var val = decode_param(match[i])
Expand Down