Skip to content
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 16 additions & 15 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,6 @@ Router.prototype.param = function param (name, fn) {
*
* @private
*/

Router.prototype.handle = function handle (req, res, callback) {
if (!callback) {
throw new TypeError('argument callback is required')
Expand Down Expand Up @@ -227,15 +226,12 @@ Router.prototype.handle = function handle (req, res, callback) {
return done(layerError)
}

// find next matching layer
let layer
let match
let route
const matchedLayers = []

while (match !== true && idx < stack.length) {
layer = stack[idx++]
match = matchLayer(layer, path)
route = layer.route
while (matchedLayers.length < 2 && idx < stack.length) {
const layer = stack[idx++]
const match = matchLayer(layer, path)
const route = layer.route

if (typeof match !== 'boolean') {
// hold on to layerError
Expand All @@ -248,12 +244,12 @@ Router.prototype.handle = function handle (req, res, callback) {

if (!route) {
// process non-route handlers normally
matchedLayers.push(layer)
continue
}

if (layerError) {
// routes do not match with a pending error
match = false
continue
}

Expand All @@ -267,18 +263,23 @@ Router.prototype.handle = function handle (req, res, callback) {

// don't even bother matching route
if (!hasMethod && method !== 'HEAD') {
match = false
continue
} else {
matchedLayers.push(layer)
}
}

// no match
if (match !== true) {
if (matchedLayers.length === 0) {
return done(layerError)
}

// prioritize strict matches over paths with parameters
const layer = matchedLayers.find((layer) => layer.layerPath === path) ?? matchedLayers[0]

if (layer) {
// store route for dispatch on change
if (route) {
req.route = route
req.route = layer.route
}

// Capture one-time layer values
Expand All @@ -291,7 +292,7 @@ Router.prototype.handle = function handle (req, res, callback) {
processParams(self.params, layer, paramcalled, req, res, function (err) {
if (err) {
next(layerError || err)
} else if (route) {
} else if (layer.route) {
layer.handleRequest(req, res, next)
} else {
trimPrefix(layer, layerError, layerPath, path)
Expand Down