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): improved customizability #2652

Merged
merged 6 commits into from
May 12, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
13 changes: 10 additions & 3 deletions deno_dist/middleware/cache/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@ import type { Context } from '../../context.ts'
import type { MiddlewareHandler } from '../../types.ts'

export const cache = (options: {
cacheName: string
cacheName: string | ((c: Context) => Promise<string> | string)
wait?: boolean
cacheControl?: string
vary?: string | string[]
keyGenerator?: (c: Context) => Promise<string> | string
}): MiddlewareHandler => {
if (!globalThis.caches) {
console.log('Cache Middleware is not enabled because caches is not defined.')
Expand Down Expand Up @@ -68,8 +69,14 @@ export const cache = (options: {
}

return async function cache(c, next) {
const key = c.req.url
const cache = await caches.open(options.cacheName)
let key = c.req.url
if (options.keyGenerator) {
key = await options.keyGenerator(c)
}

const cacheName =
typeof options.cacheName === 'function' ? await options.cacheName(c) : options.cacheName
const cache = await caches.open(cacheName)
const response = await cache.match(key)
if (response) {
return new Response(response.body, response)
Expand Down
67 changes: 67 additions & 0 deletions src/middleware/cache/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,73 @@ class Context implements ExecutionContext {
}
}

describe('Customizing Caching Keys', () => {
const app = new Hono()

const dynamicCacheName = 'dynamic-cache-name'
app.use(
'/dynamic-cache-name/*',
cache({
cacheName: async () => dynamicCacheName,
wait: true,
cacheControl: 'max-age=10',
})
)
app.get('/dynamic-cache-name/', (c) => {
return c.text('cached')
})

const dynamicCacheKey = 'dynamic-cache-key'
app.use(
'/dynamic-cache-key/*',
cache({
cacheName: 'my-app-v1',
wait: true,
cacheControl: 'max-age=10',
keyGenerator: async () => dynamicCacheKey,
})
)
app.get('/dynamic-cache-key/', (c) => {
return c.text('cached')
})

app.use(
'/dynamic-cache/*',
cache({
cacheName: async () => dynamicCacheName,
cacheControl: 'max-age=10',
keyGenerator: async () => dynamicCacheKey,
})
)
app.get('/dynamic-cache/', (c) => {
return c.text('cached')
})

const ctx = new Context()

it('Should use dynamically generated cache name', async () => {
await app.request('http://localhost/dynamic-cache-name/', undefined, ctx)
const cache = await caches.open(dynamicCacheName)
const keys = Array.from(await cache.keys())
expect(keys.length).toBe(1)
})

it('Should use dynamically generated cache key', async () => {
await app.request('http://localhost/dynamic-cache-key/')
const cache = await caches.open('my-app-v1')
const response = await cache.match(dynamicCacheKey)
expect(response).not.toBeNull()
})

it('Should retrieve cached response with dynamic cache name and key', async () => {
await app.request('http://localhost/dynamic-cache/', undefined, undefined, ctx)
const res = await app.request('http://localhost/dynamic-cache/', undefined, undefined, ctx)
expect(res).not.toBeNull()
expect(res.status).toBe(200)
expect(res.headers.get('cache-control')).toBe('max-age=10')
})
})

describe('Cache Middleware', () => {
const app = new Hono()

Expand Down
13 changes: 10 additions & 3 deletions src/middleware/cache/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@ import type { Context } from '../../context'
import type { MiddlewareHandler } from '../../types'

export const cache = (options: {
cacheName: string
cacheName: string | ((c: Context) => Promise<string> | string)
wait?: boolean
cacheControl?: string
vary?: string | string[]
keyGenerator?: (c: Context) => Promise<string> | string
}): MiddlewareHandler => {
if (!globalThis.caches) {
console.log('Cache Middleware is not enabled because caches is not defined.')
Expand Down Expand Up @@ -68,8 +69,14 @@ export const cache = (options: {
}

return async function cache(c, next) {
const key = c.req.url
const cache = await caches.open(options.cacheName)
let key = c.req.url
if (options.keyGenerator) {
key = await options.keyGenerator(c)
}

const cacheName =
typeof options.cacheName === 'function' ? await options.cacheName(c) : options.cacheName
const cache = await caches.open(cacheName)
const response = await cache.match(key)
if (response) {
return new Response(response.body, response)
Expand Down
4 changes: 4 additions & 0 deletions src/test-utils/setup-vitest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,10 @@ class MockCache {
return this.store.get(key) || null
}

async keys() {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Mocking keys() is good!

return this.store.keys()
}

async put(key: Request | string, response: Response): Promise<void> {
this.store.set(key, response)
}
Expand Down