1
- import { asArray , once } from '../util.js'
1
+ import { asArray , normalizePath , once } from '../util.js'
2
+
3
+ const normalizeRoute = ( item ) => {
4
+ const [ m , p , cb ] = asArray ( item )
2
5
3
- const normalizeRoute = ( [ m , p , cb ] ) => {
4
6
if ( typeof m === 'function' ) {
5
- return [ '*' , [ null ] , m ]
7
+ return [ '*' , [ true ] , m ]
6
8
}
7
9
8
10
if ( typeof p === 'function' ) {
9
- return [ m , [ null ] , p ]
11
+ return [ m , [ true ] , p ]
10
12
}
11
13
12
14
return [ m , asArray ( p ) , cb ]
@@ -16,8 +18,12 @@ const matchMethod = (method, expected) =>
16
18
method === expected || expected === '*' || expected === 'ALL'
17
19
18
20
const matchUrl = ( url , [ pattern ] ) => {
21
+ if ( pattern === null ) {
22
+ return false
23
+ }
24
+
19
25
if ( typeof pattern === 'string' ) {
20
- return url . startsWith ( pattern )
26
+ return url === pattern || url . startsWith ( pattern ) && url . charAt ( pattern . length ) === '/'
21
27
}
22
28
23
29
if ( pattern instanceof RegExp ) {
@@ -27,8 +33,14 @@ const matchUrl = (url, [pattern]) => {
27
33
return true
28
34
}
29
35
30
- export const createRouter = ( routes ) => async ( req , res ) => {
31
- const url = req . url
36
+ export const createRouter = ( routes , base = '/' ) => async ( req , res , next = ( ) => { } ) => {
37
+ if ( req . url . startsWith ( base ) ) {
38
+ req . url = req . url . replace ( base , '/' )
39
+ } else {
40
+ return next ( )
41
+ }
42
+
43
+ const url = normalizePath ( req . url )
32
44
const matched = routes
33
45
. map ( normalizeRoute )
34
46
. filter ( ( [ method , pattern ] ) => matchMethod ( req . method , method ) && matchUrl ( url , pattern ) )
0 commit comments