0
0
mirror of https://github.com/honojs/hono.git synced 2024-12-01 10:51:01 +00:00
hono/deno_dist/middleware/cache/index.ts
Yusuke Wada 42dc3646a0
fix(cache): clone the response (#1232)
* fix

* clone the response shortly

* add test for not found

* denoify

---------

Co-authored-by: brn <brn@b6n.ch>
2023-07-15 09:36:03 +09:00

37 lines
909 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 (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)
}
}
}