Skip to content

Commit c917f6f

Browse files
committed
fix: fix ordering of children when matching routes
1 parent 4873de5 commit c917f6f

2 files changed

Lines changed: 16 additions & 14 deletions

File tree

modules/RouteNode.js

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -75,25 +75,27 @@ export default class RouteNode {
7575
if (names.length === 1) {
7676
this.children.push(route);
7777
// Push greedy spats to the bottom of the pile
78-
this.children.sort((a, b) => {
78+
this.children.sort((left, right) => {
79+
const leftPath = left.path.split('?')[0];
80+
const rightPath = right.path.split('?')[0];
7981
// '/' last
80-
if (a.path === '/') return 1;
81-
if (b.path === '/') return -1;
82-
let aHasParams = a.parser.hasUrlParams || a.parser.hasSpatParam;
83-
let bHasParams = b.parser.hasUrlParams || b.parser.hasSpatParam;
82+
if (leftPath === '/') return 1;
83+
if (rightPath === '/') return -1;
84+
let aHasParams = left.parser.hasUrlParams || left.parser.hasSpatParam;
85+
let bHasParams = right.parser.hasUrlParams || right.parser.hasSpatParam;
8486
// No params first, sort by length descending
8587
if (!aHasParams && !bHasParams) {
86-
return a.path && b.path ? (a.path.length < b.path.length ? 1 : -1) : 0;
88+
return leftPath && rightPath ? (leftPath.length < rightPath.length ? 1 : -1) : 0;
8789
}
8890
// Params last
8991
if (aHasParams && !bHasParams) return 1;
9092
if (!aHasParams && bHasParams) return -1;
9193
// Spat params last
92-
if (!a.parser.hasSpatParam && b.parser.hasSpatParam) return -1;
93-
if (!b.parser.hasSpatParam && a.parser.hasSpatParam) return 1;
94+
if (!left.parser.hasSpatParam && right.parser.hasSpatParam) return -1;
95+
if (!right.parser.hasSpatParam && left.parser.hasSpatParam) return 1;
9496
// Sort by number of segments descending
95-
let aSegments = (a.path.match(/\//g) || []).length;
96-
let bSegments = (b.path.match(/\//g) || []).length;
97+
let aSegments = (leftPath.match(/\//g) || []).length;
98+
let bSegments = (rightPath.match(/\//g) || []).length;
9799
if (aSegments < bSegments) return 1;
98100
return 0;
99101
});

test/main.js

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -253,11 +253,11 @@ describe('RouteNode', function () {
253253

254254
it('should sort paths by length', function () {
255255
var rootNode = new RouteNode('', '')
256-
.addNode('section', '/section/:id')
257-
.addNode('index', '/')
258-
.addNode('id', '/:id')
256+
.addNode('section', '/section/:id?a')
257+
.addNode('index', '/?queryparamOfexceptionalLength')
258+
.addNode('id', '/:id?rrrr')
259259
.addNode('abo', '/abo')
260-
.addNode('about', '/about');
260+
.addNode('about', '/about?hello');
261261

262262
withoutMeta(rootNode.matchPath('/')).should.eql({name: 'index', params: {}});
263263
withoutMeta(rootNode.matchPath('/abo')).should.eql({name: 'abo', params: {}});

0 commit comments

Comments
 (0)