Skip to content

Commit

Permalink
refactor(middleware/serve-static): call getContent only once if the f…
Browse files Browse the repository at this point in the history
…ile does not exist (#2922)
  • Loading branch information
usualoma authored Jun 6, 2024
1 parent 00f32b7 commit 71f5a01
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 9 deletions.
18 changes: 12 additions & 6 deletions src/middleware/serve-static/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,21 +3,26 @@ import { serveStatic as baseServeStatic } from '.'

describe('Serve Static Middleware', () => {
const app = new Hono()
const getContent = vi.fn(async (path) => {
if (path.endsWith('not-found.txt')) {
return null
}
return `Hello in ${path}`
})

const serveStatic = baseServeStatic({
getContent: async (path) => {
if (path.endsWith('not-found.txt')) {
return null
}
return `Hello in ${path}`
},
getContent,
pathResolve: (path) => {
return `./${path}`
},
})

app.get('/static/*', serveStatic)

beforeEach(() => {
getContent.mockClear()
})

it('Should return 200 response - /static/hello.html', async () => {
const res = await app.request('/static/hello.html')
expect(res.status).toBe(200)
Expand All @@ -42,6 +47,7 @@ describe('Serve Static Middleware', () => {
const res = await app.request('/static/not-found.txt')
expect(res.status).toBe(404)
expect(await res.text()).toBe('404 Not Found')
expect(getContent).toBeCalledTimes(1)
})

it('Should not allow a directory traversal - /static/%2e%2e/static/hello.html', async () => {
Expand Down
9 changes: 6 additions & 3 deletions src/middleware/serve-static/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,9 +64,12 @@ export const serveStatic = <E extends Env = Env>(
return await next()
}
pathWithOutDefaultDocument = pathResolve(pathWithOutDefaultDocument)
content = await getContent(pathWithOutDefaultDocument, c)
if (content) {
path = pathWithOutDefaultDocument

if (pathWithOutDefaultDocument !== path) {
content = await getContent(pathWithOutDefaultDocument, c)
if (content) {
path = pathWithOutDefaultDocument
}
}
}

Expand Down

0 comments on commit 71f5a01

Please sign in to comment.