Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[PoC] refactor: implement serve-static middleware with Node.js API #3523

Draft
wants to merge 6 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
147 changes: 76 additions & 71 deletions runtime-tests/deno/middleware.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -66,79 +66,84 @@ Deno.test('JSX middleware', async () => {
assertEquals(template.toString(), '<p>1</p><p>2</p>')
})

Deno.test('Serve Static middleware', async () => {
const app = new Hono()
const onNotFound = spy(() => {})
app.all('/favicon.ico', serveStatic({ path: './runtime-tests/deno/favicon.ico' }))
app.all(
'/favicon-notfound.ico',
serveStatic({ path: './runtime-tests/deno/favicon-notfound.ico', onNotFound })
)
app.use('/favicon-notfound.ico', async (c, next) => {
await next()
c.header('X-Custom', 'Deno')
})

app.get(
'/static/*',
serveStatic({
root: './runtime-tests/deno',
onNotFound,
Deno.test({
name: 'Serve Static middleware',
sanitizeOps: false,
sanitizeResources: false,
fn: async () => {
const app = new Hono()
const onNotFound = spy(() => {})
app.all('/favicon.ico', serveStatic({ path: './runtime-tests/deno/favicon.ico' }))
app.all(
'/favicon-notfound.ico',
serveStatic({ path: './runtime-tests/deno/favicon-notfound.ico', onNotFound })
)
app.use('/favicon-notfound.ico', async (c, next) => {
await next()
c.header('X-Custom', 'Deno')
})
)

app.get(
'/dot-static/*',
serveStatic({
root: './runtime-tests/deno',
rewriteRequestPath: (path) => path.replace(/^\/dot-static/, './.static'),
})
)

app.get('/static-absolute-root/*', serveStatic({ root: dirname(fromFileUrl(import.meta.url)) }))

let res = await app.request('http://localhost/favicon.ico')
assertEquals(res.status, 200)
assertEquals(res.headers.get('Content-Type'), 'image/x-icon')
await res.body?.cancel()

res = await app.request('http://localhost/favicon-notfound.ico')
assertEquals(res.status, 404)
assertMatch(res.headers.get('Content-Type') || '', /^text\/plain/)
assertEquals(res.headers.get('X-Custom'), 'Deno')
assertSpyCall(onNotFound, 0)

res = await app.request('http://localhost/static/plain.txt')
assertEquals(res.status, 200)
assertEquals(await res.text(), 'Deno!')

res = await app.request('http://localhost/static/download')
assertEquals(res.status, 200)
assertEquals(await res.text(), 'download')

res = await app.request('http://localhost/dot-static/plain.txt')
assertEquals(res.status, 200)
assertEquals(await res.text(), 'Deno!!')
assertSpyCalls(onNotFound, 1)

res = await app.fetch({
method: 'GET',
url: 'http://localhost/static/%2e%2e/static/plain.txt',
} as Request)
assertEquals(res.status, 404)
assertEquals(await res.text(), '404 Not Found')

res = await app.request('http://localhost/static/helloworld')
assertEquals(res.status, 200)
assertEquals(await res.text(), 'Hi\n')

res = await app.request('http://localhost/static/hello.world')
assertEquals(res.status, 200)
assertEquals(await res.text(), 'Hi\n')

res = await app.request('http://localhost/static-absolute-root/plain.txt')
assertEquals(res.status, 200)
assertEquals(await res.text(), 'Deno!')
app.get(
'/static/*',
serveStatic({
root: './runtime-tests/deno',
onNotFound,
})
)

app.get(
'/dot-static/*',
serveStatic({
root: './runtime-tests/deno',
rewriteRequestPath: (path) => path.replace(/^\/dot-static/, './.static'),
})
)

app.get('/static-absolute-root/*', serveStatic({ root: dirname(fromFileUrl(import.meta.url)) }))

let res = await app.request('http://localhost/favicon.ico')
assertEquals(res.status, 200)
assertEquals(res.headers.get('Content-Type'), 'image/x-icon')
await res.body?.cancel()

res = await app.request('http://localhost/favicon-notfound.ico')
assertEquals(res.status, 404)
assertMatch(res.headers.get('Content-Type') || '', /^text\/plain/)
assertEquals(res.headers.get('X-Custom'), 'Deno')
assertSpyCall(onNotFound, 0)

res = await app.request('http://localhost/static/plain.txt')
assertEquals(res.status, 200)
assertEquals(await res.text(), 'Deno!')

res = await app.request('http://localhost/static/download')
assertEquals(res.status, 200)
assertEquals(await res.text(), 'download')

res = await app.request('http://localhost/dot-static/plain.txt')
assertEquals(res.status, 200)
assertEquals(await res.text(), 'Deno!!')
assertSpyCalls(onNotFound, 1)

res = await app.fetch({
method: 'GET',
url: 'http://localhost/static/%2e%2e/static/plain.txt',
} as Request)
assertEquals(res.status, 404)
assertEquals(await res.text(), '404 Not Found')

res = await app.request('http://localhost/static/helloworld')
assertEquals(res.status, 200)
assertEquals(await res.text(), 'Hi\n')

res = await app.request('http://localhost/static/hello.world')
assertEquals(res.status, 200)
assertEquals(await res.text(), 'Hi\n')

res = await app.request('http://localhost/static-absolute-root/plain.txt')
assertEquals(res.status, 200)
assertEquals(await res.text(), 'Deno!')
},
})

Deno.test('JWT Authentication middleware', async () => {
Expand Down
36 changes: 1 addition & 35 deletions src/adapter/bun/serve-static.ts
Original file line number Diff line number Diff line change
@@ -1,35 +1 @@
/* eslint-disable @typescript-eslint/ban-ts-comment */
import { stat } from 'node:fs/promises'
import { serveStatic as baseServeStatic } from '../../middleware/serve-static'
import type { ServeStaticOptions } from '../../middleware/serve-static'
import type { Env, MiddlewareHandler } from '../../types'

export const serveStatic = <E extends Env = Env>(
options: ServeStaticOptions<E>
): MiddlewareHandler => {
return async function serveStatic(c, next) {
const getContent = async (path: string) => {
path = path.startsWith('/') ? path : `./${path}`
// @ts-ignore
const file = Bun.file(path)
return (await file.exists()) ? file : null
}
const pathResolve = (path: string) => {
return path.startsWith('/') ? path : `./${path}`
}
const isDir = async (path: string) => {
let isDir
try {
const stats = await stat(path)
isDir = stats.isDirectory()
} catch {}
return isDir
}
return baseServeStatic({
...options,
getContent,
pathResolve,
isDir,
})(c, next)
}
}
export { serveStatic } from '../node/serve-static'
41 changes: 1 addition & 40 deletions src/adapter/deno/serve-static.ts
Original file line number Diff line number Diff line change
@@ -1,40 +1 @@
import type { ServeStaticOptions } from '../../middleware/serve-static'
import { serveStatic as baseServeStatic } from '../../middleware/serve-static'
import type { Env, MiddlewareHandler } from '../../types'

// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const { open, lstatSync } = Deno

export const serveStatic = <E extends Env = Env>(
options: ServeStaticOptions<E>
): MiddlewareHandler => {
return async function serveStatic(c, next) {
const getContent = async (path: string) => {
try {
const file = await open(path)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return file ? (file.readable as any) : null
} catch (e) {
console.warn(`${e}`)
}
}
const pathResolve = (path: string) => {
return path.startsWith('/') ? path : `./${path}`
}
const isDir = (path: string) => {
let isDir
try {
const stat = lstatSync(path)
isDir = stat.isDirectory
} catch {}
return isDir
}
return baseServeStatic({
...options,
getContent,
pathResolve,
isDir,
})(c, next)
}
}
export { serveStatic } from '../node/serve-static'

Check warning on line 1 in src/adapter/deno/serve-static.ts

View check run for this annotation

Codecov / codecov/patch

src/adapter/deno/serve-static.ts#L1

Added line #L1 was not covered by tests
Loading
Loading