@@ -2,21 +2,21 @@ const path = require('path')
2
2
const fs = require ( 'fs' )
3
3
const qs = require ( 'querystring' )
4
4
5
- const paramPattern = / : ( [ ^ \ /] + ) /
5
+ const paramPattern = / : ( [ ^ / ] + ) /
6
6
// takes routes and decorates them with a 'match' method that will return { params, query } if a path matches
7
- function addMatch ( route ) {
7
+ function addMatch ( route ) {
8
8
let routePath = route . path
9
9
let paramNames = [ ]
10
10
let matched
11
11
// find any paths prefixed with a `:`, and treat them as capture groups
12
- while ( matched = routePath . match ( paramPattern ) ) {
13
- routePath = routePath . replace ( paramPattern , '([^\?\ /]+)' )
12
+ while ( ( matched = routePath . match ( paramPattern ) ) !== null ) {
13
+ routePath = routePath . replace ( paramPattern , '([^? /]+)' )
14
14
paramNames . push ( matched [ 1 ] )
15
15
}
16
16
// if a route ends with `index`, allow matching that route without matching the `index` part
17
17
if ( path . basename ( routePath ) === 'index' ) {
18
18
route . isIndex = true
19
- routePath = routePath . replace ( / \/ i n d e x $ / , '\ /?(:?index)?' )
19
+ routePath = routePath . replace ( / \/ i n d e x $ / , '/?(:?index)?' )
20
20
}
21
21
// create a regex with our path
22
22
let pattern = new RegExp ( `^${ routePath } (\\?(.*)|$)` , 'i' )
@@ -36,7 +36,7 @@ function addMatch(route) {
36
36
}
37
37
38
38
// recursively searches for all js files inside a directory tree, and returns their full paths
39
- function findRoutes ( dir ) {
39
+ function findRoutes ( dir ) {
40
40
let files = fs . readdirSync ( dir )
41
41
let resolve = f => path . join ( dir , f )
42
42
let routes = files . filter ( f => path . extname ( f ) === '.js' ) . map ( resolve )
@@ -45,8 +45,10 @@ function findRoutes(dir) {
45
45
}
46
46
47
47
const val = v => ( typeof v === 'undefined' ? 0 : v )
48
- module . exports = function router ( routesDir ) {
48
+ module . exports = function router ( routesDir , config ) {
49
49
const routes = findRoutes ( routesDir )
50
+ // if filter function is set, filter routes
51
+ . filter ( config && config . filter || function ( ) { return true } )
50
52
// require route files, then add a 'path' property to them
51
53
// the path is in the form of '/path/file', relative to routesDir
52
54
. map ( routeFile => {
@@ -68,7 +70,7 @@ module.exports = function router(routesDir) {
68
70
. sort ( ( a , b ) => val ( a . priority ) < val ( b . priority ) ? 1 : - 1 )
69
71
70
72
// generated match method - call with a req object to get a route.
71
- return function match ( req ) {
73
+ return function match ( req ) {
72
74
let routeFn = r => r [ req . method ] || ( typeof r === 'function' && r )
73
75
let found = routes . find ( r => {
74
76
let matched = r . match ( req . url )
0 commit comments