-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
72 lines (61 loc) · 2.67 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
const fs = require('fs')
const path = require('path')
function routes (directory, directoryRoot = null) {
let _routes = []
// These shenanigans are for Windows path silliness support.
let directoryForRegExp = directory
if (process.platform === 'win32') {
directoryForRegExp = directoryForRegExp.replace(/\\/g, '\\\\')
}
if (directoryRoot === null) directoryRoot = new RegExp(`^.*${directoryForRegExp.replace('.', '\\.')}`)
const files = fs.readdirSync(directory, {withFileTypes: true})
files.forEach(file => {
if (file.isDirectory()) {
//
// Directory.
//
if (file.name === 'node_modules' || file.name.startsWith('.')) {
// Skip.
return
}
// Recurse.
_routes = _routes.concat(routes(path.join(directory, file.name), directoryRoot))
} else if (file.isFile() && (file.name.endsWith('.js') || file.name.endsWith('.cjs') || file.name.endsWith('.mjs'))) {
//
// File.
//
let routeCallbackFilePath = path.resolve(path.join(directory, file.name))
let routeUrlPath = path.join(directory.replace(directoryRoot, ''), file.name)
// Note: the regexp is written so that it will strip the leading slash properly
// ===== on both Linux-style and Windows environments.
routeUrlPath = routeUrlPath.replace(/\/?\\?index(.*?)\.js$/, '$1')
routeUrlPath = routeUrlPath.replace(/\/?\\?index(.*?)\.cjs$/, '$1')
routeUrlPath = routeUrlPath.replace(/\/?\\?index(.*?)\.mjs$/, '$1')
routeUrlPath = routeUrlPath.replace('.js', '')
routeUrlPath = routeUrlPath.replace('.cjs', '')
routeUrlPath = routeUrlPath.replace('.mjs', '')
routeUrlPath = routeUrlPath.replace(/\/$/, '')
// Handle parameter formatting:
//
// _ : parameter delimeter (/:)
// __ : static path fragment delimeter (/)
//
// e.g., /person/index_personId__book__bookId becomes:
// /person/:personId/book/:bookId
routeUrlPath = routeUrlPath.replace(/__/g, '/')
routeUrlPath = routeUrlPath.replace(/_/g, '/:')
// On Windows, the file path slashes are backwards so we have to reverse them.
if (process.platform === 'win32') {
// Since the code replacing the forward slash at the end will not have caught a backslash at the end
// on Windows, do that now.
routeUrlPath = routeUrlPath.replace(/\\$/, '')
// Replace all backslashes with forwardslashes.
routeUrlPath = routeUrlPath.replace(/\\/g, '/')
}
if (!routeUrlPath.startsWith('/')) routeUrlPath = `/${routeUrlPath}`
_routes.push({path: routeUrlPath, callback: routeCallbackFilePath})
}
})
return _routes
}
module.exports = routes