Skip to content

Commit

Permalink
feat(serve-static): add onFound option (#3396)
Browse files Browse the repository at this point in the history
  • Loading branch information
yusukebe authored Sep 10, 2024
1 parent 3c4d4c2 commit a86f3ce
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 1 deletion.
6 changes: 6 additions & 0 deletions src/middleware/serve-static/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,11 @@ describe('Serve Static Middleware', () => {
isDir: (path) => {
return path === 'static/hello.world'
},
onFound: (path, c) => {
if (path.endsWith('hello.html')) {
c.header('X-Custom', `Found the file at ${path}`)
}
},
})

app.get('/static/*', serveStatic)
Expand All @@ -32,6 +37,7 @@ describe('Serve Static Middleware', () => {
expect(res.headers.get('Content-Encoding')).toBeNull()
expect(res.headers.get('Content-Type')).toMatch(/^text\/html/)
expect(await res.text()).toBe('Hello in ./static/hello.html')
expect(res.headers.get('X-Custom')).toBe('Found the file at ./static/hello.html')
})

it('Should return 200 response - /static/sub', async () => {
Expand Down
3 changes: 2 additions & 1 deletion src/middleware/serve-static/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ export type ServeStaticOptions<E extends Env = Env> = {
precompressed?: boolean
mimes?: Record<string, string>
rewriteRequestPath?: (path: string) => string
onFound?: (path: string, c: Context<E>) => void | Promise<void>
onNotFound?: (path: string, c: Context<E>) => void | Promise<void>
}

Expand Down Expand Up @@ -128,7 +129,7 @@ export const serveStatic = <E extends Env = Env>(
}
}
}

await options.onFound?.(path, c)
return c.body(content)
}

Expand Down

0 comments on commit a86f3ce

Please sign in to comment.