@@ -28,41 +28,30 @@ export function compareRoute(
28
28
route1 : Pick < RouteEntry , 'verb' | 'path' > ,
29
29
route2 : Pick < RouteEntry , 'verb' | 'path' > ,
30
30
) : number {
31
- // First check verb
32
- const verb1 = HTTP_VERBS [ route1 . verb . toLowerCase ( ) ] || HTTP_VERBS . get ;
33
- const verb2 = HTTP_VERBS [ route2 . verb . toLowerCase ( ) ] || HTTP_VERBS . get ;
34
- if ( verb1 !== verb2 ) return verb1 - verb2 ;
35
-
36
- // Then check the path tokens
31
+ // First check the path tokens
37
32
const path1 = route1 . path . replace ( / { ( [ ^ } ] * ) } ( \/ | $ ) / g, ':$1$2' ) ;
38
33
const path2 = route2 . path . replace ( / { ( [ ^ } ] * ) } ( \/ | $ ) / g, ':$1$2' ) ;
39
34
const tokensForPath1 : pathToRegExp . Token [ ] = parse ( path1 ) ;
40
35
const tokensForPath2 : pathToRegExp . Token [ ] = parse ( path2 ) ;
41
36
42
- // Longer path comes before shorter path
43
- if ( tokensForPath1 . length < tokensForPath2 . length ) {
44
- return 1 ;
45
- } else if ( tokensForPath1 . length > tokensForPath2 . length ) {
46
- return - 1 ;
47
- }
37
+ const length =
38
+ tokensForPath1 . length > tokensForPath2 . length
39
+ ? tokensForPath1 . length
40
+ : tokensForPath2 . length ;
48
41
49
- // Now check token by token
50
- for ( let i = 0 ; i < tokensForPath1 . length ; i ++ ) {
42
+ for ( let i = 0 ; i < length ; i ++ ) {
51
43
const token1 = tokensForPath1 [ i ] ;
52
44
const token2 = tokensForPath2 [ i ] ;
53
- if ( typeof token1 === 'string' && typeof token2 === 'string' ) {
54
- if ( token1 < token2 ) return - 1 ;
55
- else if ( token1 > token2 ) return 1 ;
56
- } else if ( typeof token1 === 'string' && typeof token2 === 'object' ) {
57
- // token 1 is a literal while token 2 is a parameter
58
- return - 1 ;
59
- } else if ( typeof token1 === 'object' && typeof token2 === 'string' ) {
60
- // token 1 is a parameter while token 2 is a literal
61
- return 1 ;
62
- } else {
63
- // Both token are parameters. Treat as equal weight.
64
- }
45
+ if ( token1 === token2 ) continue ;
46
+ if ( token1 === undefined ) return 1 ;
47
+ if ( token2 === undefined ) return - 1 ;
48
+ if ( token1 < token2 ) return - 1 ;
49
+ if ( token1 > token2 ) return 1 ;
65
50
}
51
+ // Then check verb
52
+ const verb1 = HTTP_VERBS [ route1 . verb . toLowerCase ( ) ] || HTTP_VERBS . get ;
53
+ const verb2 = HTTP_VERBS [ route2 . verb . toLowerCase ( ) ] || HTTP_VERBS . get ;
54
+ if ( verb1 !== verb2 ) return verb1 - verb2 ;
66
55
return 0 ;
67
56
}
68
57
@@ -77,7 +66,8 @@ function parse(path: string) {
77
66
// The string can be /orders/count
78
67
tokens . push ( ...p . split ( '/' ) . filter ( Boolean ) ) ;
79
68
} else {
80
- tokens . push ( p ) ;
69
+ // Use `{}` for wildcard as they are larger than any other ascii chars
70
+ tokens . push ( `{}` ) ;
81
71
}
82
72
} ) ;
83
73
return tokens ;
0 commit comments