This repository has been archived by the owner on Apr 6, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
middleware.ts
81 lines (68 loc) · 2.24 KB
/
middleware.ts
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
73
74
75
76
77
78
79
80
81
import hasha from 'hasha'
import { relative } from 'pathe'
import table from 'table'
import isPrimitive from 'is-primitive'
import { isDebug } from 'std-env'
import { genArrayFromRaw, genDynamicImport, genImport } from 'mlly'
import type { ServerMiddleware } from '../../server/middleware'
import virtual from './virtual'
const unique = (arr: any[]) => Array.from(new Set(arr))
export function middleware (getMiddleware: () => ServerMiddleware[]) {
const getImportId = p => '_' + hasha(p).substr(0, 6)
let lastDump = ''
return virtual({
'#server-middleware': {
load: () => {
const middleware = getMiddleware()
if (isDebug) {
const dumped = dumpMiddleware(middleware)
if (dumped !== lastDump) {
lastDump = dumped
if (middleware.length) {
console.log(dumped)
}
}
}
// Imports take priority
const imports = unique(middleware.filter(m => m.lazy === false).map(m => m.handle))
// Lazy imports should fill in the gaps
const lazyImports = unique(middleware.filter(m => m.lazy !== false && !imports.includes(m.handle)).map(m => m.handle))
return `
${imports.map(handle => `${genImport(handle, getImportId(handle))};`).join('\n')}
${lazyImports.map(handle => `const ${getImportId(handle)} = ${genDynamicImport(handle)};`).join('\n')}
const middleware = ${genArrayFromRaw(middleware.map(m => ({
route: JSON.stringify(m.route),
handle: getImportId(m.handle),
lazy: m.lazy || true,
promisify: m.promisify !== undefined ? m.promisify : true
})))};
export default middleware
`
}
}
})
}
function dumpMiddleware (middleware: ServerMiddleware[]) {
const data = middleware.map(({ route, handle, ...props }) => {
return [
(route && route !== '/') ? route : '*',
relative(process.cwd(), handle as string),
dumpObject(props)
]
})
return table.table([
['Route', 'Handle', 'Options'],
...data
], {
singleLine: true,
border: table.getBorderCharacters('norc')
})
}
function dumpObject (obj: any) {
const items = []
for (const key in obj) {
const val = obj[key]
items.push(`${key}: ${isPrimitive(val) ? val : JSON.stringify(val)}`)
}
return items.join(', ')
}