-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathfilesystem.ts
60 lines (51 loc) · 1.61 KB
/
filesystem.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
// TODO(#323): remove on v6
import { resolve } from 'path'
import { Router } from 'express'
import glob from 'glob'
import file from './file'
import redirect from './redirect'
export type FilesystemHandleOptions = {
indexFile: string
notFoundFile: string
}
function filesystemOptions(
value: string | Partial<FilesystemHandleOptions>
): FilesystemHandleOptions {
const options = typeof value === 'string' ? { notFoundFile: value } : value
return {
indexFile: 'index.html',
notFoundFile: '404.html',
...options,
}
}
/**
* @deprecated use filesytem2/* instead
*/
export default function filesystem(
path: string,
notFoundPage: string | Partial<FilesystemHandleOptions>,
options?: {
defaultHeaders?: Record<string, string>
api?: boolean
}
) {
const router = Router()
const fileSystemOptions = filesystemOptions(notFoundPage)
const indexFile = '/' + fileSystemOptions.indexFile
const cwd = resolve(process.cwd(), path)
const files = Array.from(
new Set(glob.sync('**/*', { cwd, nodir: true })).values()
).sort()
for (const filePath of files) {
const webPath = '/' + filePath // => /en/index.html
if (webPath.endsWith(indexFile)) {
const basePath = webPath.slice(0, -10)
router.get(webPath, redirect(basePath)) // redirect /en/index.html => /en/
router.get(basePath, file(resolve(cwd, filePath), 200, options)) // load /en/index.html on /en/
} else {
router.get(webPath, file(resolve(cwd, filePath), 200, options)) // load /en/other.html
}
}
router.use(file(resolve(cwd, fileSystemOptions.notFoundFile), 404, options))
return router
}