-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
44 lines (37 loc) · 1.41 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
import { Router } from 'express'
import globPromise from './globPromise'
// Hoist global html template string function
global.html = (templateStrings, ...values) => String.raw(templateStrings, ...values)
export default async () => {
let handler = Router()
let dirArray = await globPromise('./pages/')
let dynamicRoutesRegExp = /\[.+\]/
dirArray.forEach(async (fsPath, i, arr) => {
let segmentedRoute = fsPath.split('/')
segmentedRoute.shift()
let lastSegmentedRoute = segmentedRoute[segmentedRoute.length - 1]
segmentedRoute[segmentedRoute.length - 1] = lastSegmentedRoute.replace('.page.js', '')
let mountPath = ''
segmentedRoute.forEach((route, i, arr) => {
if (i == arr.length - 1 && route == 'index') {
mountPath += '/'
} else if (dynamicRoutesRegExp.test(route)) {
mountPath += '/:' + route.replace('[', '').replace(']', '').trim()
} else {
mountPath += '/' + route.trim()
}
})
handler.all(mountPath, async (req, res, next) => {
try {
return res.send(await (await import('./' + fsPath)).default({
req: req,
res: res,
params: req.params
}))
} catch (err) {
next(err)
}
})
})
return handler
}