-
-
Notifications
You must be signed in to change notification settings - Fork 660
/
Copy pathserve-static.ts
56 lines (47 loc) · 1.4 KB
/
serve-static.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
// @denoify-ignore
/* eslint-disable @typescript-eslint/ban-ts-comment */
import { existsSync } from 'fs'
import type { Context } from '../../context'
import type { Next } from '../../types'
import { getFilePath } from '../../utils/filepath'
import { getMimeType } from '../../utils/mime'
// @ts-ignore
const { file } = Bun
export type ServeStaticOptions = {
root?: string
path?: string
rewriteRequestPath?: (path: string) => string
}
const DEFAULT_DOCUMENT = 'index.html'
export const serveStatic = (options: ServeStaticOptions = { root: '' }) => {
return async (c: Context, next: Next) => {
// Do nothing if Response is already set
if (c.finalized) {
await next()
return
}
const url = new URL(c.req.url)
const filename = options.path ?? decodeURI(url.pathname)
let path = getFilePath({
filename: options.rewriteRequestPath ? options.rewriteRequestPath(filename) : filename,
root: options.root,
defaultDocument: DEFAULT_DOCUMENT,
})
if (!path) return await next()
path = `./${path}`
if (existsSync(path)) {
const content = file(path)
if (content) {
const mimeType = getMimeType(path)
if (mimeType) {
c.header('Content-Type', mimeType)
}
// Return Response object
return c.body(content)
}
}
console.warn(`Static file: ${path} is not found`)
await next()
return
}
}