mirror of
https://github.com/honojs/hono.git
synced 2024-11-29 17:46:30 +01:00
bd36ad10fc
* feat(dev): Introduce "dev" helper * feat(dev): Expose "dev" helper * refactor: Use "named function" in some middleware. * feat: `app.showRoutes()` is now deprecated. Use `showRoutes()` in `helper` instead. * refactor: export RouterRoute interface for utility * refactor: remove captureRouteStackTrace, add inspectRoutes `captureRouteStackTrace` will be implemented after some more thought. Instead, I added `inspectRoutes` to get routes as data. * test: add tests for helper/dev/index.ts * fix: run `format:fix` * refactor: use named functions for middleware * chore: denoify * docs: tweaks deprecation warning message * refactor(dev): Simplification of showList options * chore: denoify
37 lines
920 B
TypeScript
37 lines
920 B
TypeScript
import type { MiddlewareHandler } from '../../types.ts'
|
|
|
|
export const cache = (options: {
|
|
cacheName: string
|
|
wait?: boolean
|
|
cacheControl?: string
|
|
}): MiddlewareHandler => {
|
|
if (options.wait === undefined) {
|
|
options.wait = false
|
|
}
|
|
|
|
const addHeader = (response: Response) => {
|
|
if (options.cacheControl) response.headers.set('Cache-Control', options.cacheControl)
|
|
}
|
|
|
|
return async function cache(c, next) {
|
|
const key = c.req.url
|
|
const cache = await caches.open(options.cacheName)
|
|
const response = await cache.match(key)
|
|
if (!response) {
|
|
await next()
|
|
if (!c.res.ok) {
|
|
return
|
|
}
|
|
addHeader(c.res)
|
|
const response = c.res.clone()
|
|
if (options.wait) {
|
|
await cache.put(key, response)
|
|
} else {
|
|
c.executionCtx.waitUntil(cache.put(key, response))
|
|
}
|
|
} else {
|
|
return new Response(response.body, response)
|
|
}
|
|
}
|
|
}
|