Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(cache): add duration option #3367

Draft
wants to merge 10 commits into
base: main
Choose a base branch
from
25 changes: 23 additions & 2 deletions src/middleware/cache/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
* @param {boolean} [options.wait=false] - A boolean indicating if Hono should wait for the Promise of the `cache.put` function to resolve before continuing with the request. Required to be true for the Deno environment.
* @param {string} [options.cacheControl] - A string of directives for the `Cache-Control` header.
* @param {string | string[]} [options.vary] - Sets the `Vary` header in the response. If the original response header already contains a `Vary` header, the values are merged, removing any duplicates.
* @param {number} [options.duration] - A number of seconds to cache the response.
* @param {Function} [options.keyGenerator] - Generates keys for every request in the `cacheName` store. This can be used to cache data based on request parameters or context parameters.
* @returns {MiddlewareHandler} The middleware handler function.
* @throws {Error} If the `vary` option includes "*".
Expand All @@ -36,6 +37,7 @@
wait?: boolean
cacheControl?: string
vary?: string | string[]
duration?: number
keyGenerator?: (c: Context) => Promise<string> | string
}): MiddlewareHandler => {
if (!globalThis.caches) {
Expand Down Expand Up @@ -72,7 +74,9 @@
let [name, value] = directive.trim().split('=', 2)
name = name.toLowerCase()
if (!existingDirectives.includes(name)) {
c.header('Cache-Control', `${name}${value ? `=${value}` : ''}`, { append: true })
c.header('Cache-Control', `${name}${value ? `=${value}` : ''}`, {
append: true,
})
}
}
}
Expand All @@ -98,6 +102,8 @@
}
}

const expirationHeader = 'Hono-Cache-Expiration'

return async function cache(c, next) {
let key = c.req.url
if (options.keyGenerator) {
Expand All @@ -109,7 +115,18 @@
const cache = await caches.open(cacheName)
const response = await cache.match(key)
if (response) {
return new Response(response.body, response)
if (options.duration) {
const duration = Number(response.headers.get(expirationHeader))
if (duration) {
const now = Date.now()
response.headers.delete(expirationHeader)
ryuapp marked this conversation as resolved.
Show resolved Hide resolved
if (duration > now) {
return new Response(response.body, response)
}
}

Check warning on line 126 in src/middleware/cache/index.ts

View check run for this annotation

Codecov / codecov/patch

src/middleware/cache/index.ts#L119-L126

Added lines #L119 - L126 were not covered by tests
} else {
return new Response(response.body, response)
}
}

await next()
Expand All @@ -118,6 +135,10 @@
}
addHeader(c)
const res = c.res.clone()
if (options.duration) {
const expiration = Date.now() + options.duration * 1000
res.headers.set(expirationHeader, String(expiration))

Check warning on line 140 in src/middleware/cache/index.ts

View check run for this annotation

Codecov / codecov/patch

src/middleware/cache/index.ts#L139-L140

Added lines #L139 - L140 were not covered by tests
ryuapp marked this conversation as resolved.
Show resolved Hide resolved
}
if (options.wait) {
await cache.put(key, res)
} else {
Expand Down
Loading