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
Draft
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 69 additions & 0 deletions runtime_tests/deno/cache.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import { Hono } from '../../src/hono.ts'
import { cache } from '../../src/middleware/cache/index.ts'
import { expect } from '@std/expect'
import { FakeTime } from '@std/testing/time'

Deno.test('Should return cached response', async () => {
const c = await caches.open('my-app')
await c.delete('http://localhost')

let oneTimeWord = 'Hello Hono'

const app = new Hono()
app.use(
'/',
cache({
cacheName: 'my-app',
wait: true,
})
)
app.get('/', (c) => {
const result = oneTimeWord
oneTimeWord = 'Not Found'
return c.text(result)
})

await app.request('http://localhost')
const res = await app.request('http://localhost')
expect(await res.text()).toBe('Hello Hono')
expect(res.headers.get('Hono-Cached-Time')).toBeNull()
expect(res).not.toBeNull()
expect(res.status).toBe(200)
})

Deno.test(
{
name: 'Should not return cached response over duration',
sanitizeResources: false,
},
async () => {
const time = new FakeTime()
const c = await caches.open('my-app')
await c.delete('http://localhost')

let oneTimeWord = 'Hello Hono'

const app = new Hono()
app.use(
'/',
cache({
cacheName: 'my-app',
wait: true,
duration: 60,
})
)
app.get('/', (c) => {
const result = oneTimeWord
oneTimeWord = 'Not Found'
return c.text(result)
})

await app.request('http://localhost')
await time.tickAsync(60000)
const res = await app.request('http://localhost')
expect(await res.text()).toBe('Not Found')
expect(res.headers.get('Hono-Cached-Time')).toBeNull()
expect(res).not.toBeNull()
expect(res.status).toBe(200)
}
)
1 change: 1 addition & 0 deletions runtime_tests/deno/deno.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
],
"imports": {
"@std/assert": "jsr:@std/assert@^1.0.3",
"@std/expect": "jsr:@std/expect@^1.0.2",
"@std/testing": "jsr:@std/testing@^1.0.1",
"hono/jsx/jsx-runtime": "../../src/jsx/jsx-runtime.ts"
}
Expand Down
42 changes: 31 additions & 11 deletions runtime_tests/deno/deno.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

20 changes: 18 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 cachedTime = 'Hono-Cached-Time'

return async function cache(c, next) {
let key = c.req.url
if (options.keyGenerator) {
Expand All @@ -109,7 +115,14 @@
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(cachedTime)) + options.duration * 1000
if (duration && duration > Date.now()) {
return new Response(response.body, response).headers.delete(cachedTime)
ryuapp marked this conversation as resolved.
Show resolved Hide resolved
}

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

View check run for this annotation

Codecov / codecov/patch

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

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

await next()
Expand All @@ -118,6 +131,9 @@
}
addHeader(c)
const res = c.res.clone()
if (options.duration) {
res.headers.set(cachedTime, String(Date.now()))

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

View check run for this annotation

Codecov / codecov/patch

src/middleware/cache/index.ts#L135

Added line #L135 was not covered by tests
}
if (options.wait) {
await cache.put(key, res)
} else {
Expand Down
Loading