Skip to content

Commit

Permalink
fix(matcher): leave catchall routes at the end
Browse files Browse the repository at this point in the history
Fix #1435
  • Loading branch information
posva committed Jun 9, 2022
1 parent 0478512 commit 77f0998
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
9 changes: 9 additions & 0 deletions __tests__/matcher/pathRanking.spec.ts
Expand Up @@ -143,6 +143,15 @@ describe('Path ranking', () => {
})
})

it('puts catchall param after same prefix', () => {
possibleOptions.forEach(options => {
checkPathOrder([
['/a', options],
['/a/:a(.*)*', options],
])
})
})

it('sensitive should go before non sensitive', () => {
checkPathOrder([
['/Home', { sensitive: true }],
Expand Down
15 changes: 15 additions & 0 deletions src/matcher/pathParserRanker.ts
Expand Up @@ -329,6 +329,10 @@ export function comparePathParserScore(a: PathParser, b: PathParser): number {

i++
}
if (Math.abs(bScore.length - aScore.length) === 1) {
if (isLastScoreNegative(aScore)) return 1
if (isLastScoreNegative(bScore)) return -1
}

// if a and b share the same score entries but b has more, sort b first
return bScore.length - aScore.length
Expand All @@ -339,3 +343,14 @@ export function comparePathParserScore(a: PathParser, b: PathParser): number {
// ? -1
// : 0
}

/**
* This allows detecting splats at the end of a path: /home/:id(.*)*
*
* @param score - score to check
* @returns true if the last entry is negative
*/
function isLastScoreNegative(score: PathParser['score']): boolean {
const last = score[score.length - 1]
return score.length > 0 && last[last.length - 1] < 0
}

0 comments on commit 77f0998

Please sign in to comment.