Skip to content

Commit

Permalink
fix(serve-static): enable in any order (#244)
Browse files Browse the repository at this point in the history
Close #243
  • Loading branch information
yusukebe authored May 18, 2022
1 parent 3c2e862 commit 9c3eb27
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 2 deletions.
36 changes: 36 additions & 0 deletions src/middleware/serve-static/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import type { Context } from '../../context'
import type { Next } from '../../hono'
import { Hono } from '../../hono'
import { serveStatic } from '.'

Expand Down Expand Up @@ -62,3 +64,37 @@ describe('ServeStatic Middleware', () => {
expect(res.headers.get('Content-Type')).toBe('text/html; charset=utf-8')
})
})

describe('With middleware', () => {
const app = new Hono()
const md1 = async (c: Context, next: Next) => {
await next()
c.res.headers.append('x-foo', 'bar')
}
const md2 = async (c: Context, next: Next) => {
await next()
c.res.headers.append('x-foo2', 'bar2')
}

app.use('/static/*', md1)
app.use('/static/*', serveStatic({ root: './assets' }))
app.use('/static/*', md2)
app.get('/static/foo', (c) => {
return c.text('bar')
})

it('Should return plain.txt with correct headers', async () => {
const res = await app.request('http://localhost/static/plain.txt')
expect(res.status).toBe(200)
expect(await res.text()).toBe('This is plain.txt')
expect(res.headers.get('Content-Type')).toBe('text/plain; charset=utf-8')
expect(res.headers.get('x-foo')).toBe('bar')
expect(res.headers.get('x-foo2')).toBe('bar2')
})

it('Should return 200 Response', async () => {
const res = await app.request('http://localhost/static/foo')
expect(res.status).toBe(200)
expect(await res.text()).toBe('bar')
})
})
10 changes: 8 additions & 2 deletions src/middleware/serve-static/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,11 @@ const DEFAULT_DOCUMENT = 'index.html'
// This middleware is available only on Cloudflare Workers.
export const serveStatic = (opt: Options = { root: '' }) => {
return async (c: Context, next: Next) => {
await next()
// Do nothing if Response is already set
if (c.res) {
await next()
}

const url = new URL(c.req.url)

const path = getKVFilePath({
Expand All @@ -27,9 +31,11 @@ export const serveStatic = (opt: Options = { root: '' }) => {
if (mimeType) {
c.header('Content-Type', mimeType)
}
c.res = c.body(content)
// Return Response object
return c.body(content)
} else {
console.warn(`Static file: ${path} is not found`)
await next()
}
}
}

0 comments on commit 9c3eb27

Please sign in to comment.