index.test.ts
This file
Path
src/middleware/cache/index.test.ts
1,211 lines · 38.6 KiB · TypeScript
Last changed by
chore: let oxfmt sort imports instead of eslint (#5442)Yusuke Wadabefore adoption859e2c2
History of this fileTake it
The walk stopped after 200 commits: lines older than f0b094d point at it.
Merge commit from forkYusuke Wadabefore adoptionf0b094d
line 1why, one step back1import { vi } from 'vitest'chore: let oxfmt sort imports instead of eslint (#5442)Yusuke Wadabefore adoption859e2c2
line 2why, one step back2import { cache } from '.'Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 3–103why, one step back3import type { ExecutionContext } from '../../context'4import { Hono } from '../../hono'56// Mock7type StoreMap = Map<string | Request, Response>89class MockCache {10 name: string11 store: StoreMap1213 constructor(name: string, store: StoreMap) {14 this.name = name15 this.store = store16 }1718 async match(key: Request | string): Promise<Response | null> {19 return this.store.get(key) || null20 }2122 async keys() {23 return this.store.keys()24 }2526 async put(key: Request | string, response: Response): Promise<void> {27 this.store.set(key, response)28 }29}3031const globalStore: StoreMap = new Map()3233vi.stubGlobal('caches', {34 open: (name: string) => {35 return new MockCache(name, globalStore)36 },37})3839class Context implements ExecutionContext {40 passThroughOnException(): void {41 throw new Error('Method not implemented.')42 }43 async waitUntil(promise: Promise<unknown>): Promise<void> {44 await promise45 }46 // eslint-disable-next-line @typescript-eslint/no-explicit-any47 props: any48}4950describe('Customizing Caching Keys', () => {51 const app = new Hono()5253 const dynamicCacheName = 'dynamic-cache-name'54 app.use(55 '/dynamic-cache-name/*',56 cache({57 cacheName: async () => dynamicCacheName,58 wait: true,59 cacheControl: 'max-age=10',60 })61 )62 app.get('/dynamic-cache-name/', (c) => {63 return c.text('cached')64 })6566 const dynamicCacheKey = 'dynamic-cache-key'67 app.use(68 '/dynamic-cache-key/*',69 cache({70 cacheName: 'my-app-v1',71 wait: true,72 cacheControl: 'max-age=10',73 keyGenerator: async () => dynamicCacheKey,74 })75 )76 app.get('/dynamic-cache-key/', (c) => {77 return c.text('cached')78 })7980 app.use(81 '/dynamic-cache/*',82 cache({83 cacheName: async () => dynamicCacheName,84 cacheControl: 'max-age=10',85 keyGenerator: async () => dynamicCacheKey,86 })87 )88 app.get('/dynamic-cache/', (c) => {89 return c.text('cached')90 })9192 const ctx = new Context()9394 it('Should use dynamically generated cache name', async () => {95 await app.request('http://localhost/dynamic-cache-name/', undefined, ctx)96 const cache = await caches.open(dynamicCacheName)97 const keys = Array.from(await cache.keys())98 expect(keys.length).toBe(1)99 })100101 it('Should use dynamically generated cache key', async () => {102 await app.request('http://localhost/dynamic-cache-key/')103 const cache = await caches.open('my-app-v1')Merge pull request #5154 from honojs/nextYusuke Wadabefore adoptionb0c2d90
lines 104–106why, one step back104 const response = await cache.match(105 'http://localhost/.hono/cache?__hono_cache_key=dynamic-cache-key&__hono_cache_method=GET'106 )Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 107–158why, one step back107 expect(response).not.toBeNull()108 })109110 it('Should retrieve cached response with dynamic cache name and key', async () => {111 await app.request('http://localhost/dynamic-cache/', undefined, undefined, ctx)112 const res = await app.request('http://localhost/dynamic-cache/', undefined, undefined, ctx)113 expect(res).not.toBeNull()114 expect(res.status).toBe(200)115 expect(res.headers.get('cache-control')).toBe('max-age=10')116 })117})118119describe('Cache Middleware', () => {120 const app = new Hono()121122 let count = 1123 // wait, because this is test.124 // You don't have to set `wait: true`.125 app.use('/wait/*', cache({ cacheName: 'my-app-v1', wait: true, cacheControl: 'max-age=10' }))126 app.get('/wait/', (c) => {127 c.header('X-Count', `${count}`)128 count++129 return c.text('cached')130 })131132 // Default, use `waitUntil`133 app.use('/not-wait/*', cache({ cacheName: 'my-app-v1', cacheControl: 'max-age=10' }))134 app.get('/not-wait/', (c) => {135 return c.text('not cached')136 })137138 app.use('/wait2/*', cache({ cacheName: 'my-app-v1', wait: true, cacheControl: 'max-age=10' }))139 app.use('/wait2/*', cache({ cacheName: 'my-app-v1', wait: true, cacheControl: 'Max-Age=20' }))140 app.get('/wait2/', (c) => {141 return c.text('cached')142 })143144 app.use('/wait3/*', cache({ cacheName: 'my-app-v1', wait: true, cacheControl: 'max-age=10' }))145 app.use(146 '/wait3/private/*',147 cache({ cacheName: 'my-app-v1', wait: true, cacheControl: 'private' })148 )149 app.get('/wait3/private/', (c) => {150 return c.text('cached')151 })152153 app.use('/wait4/*', cache({ cacheName: 'my-app-v1', wait: true, cacheControl: 'max-age=10' }))154 app.get('/wait4/', (c) => {155 c.header('Cache-Control', 'private')156 return c.text('cached')157 })158fix(cache): deduplicate Cache-Control directives case-insensitively (#5025)nyxst4ckbefore adoptiona48c8bf
lines 159–164why, one step back159 app.use('/wait5/*', cache({ cacheName: 'my-app-v1', wait: true, cacheControl: 'max-age=10' }))160 app.get('/wait5/', (c) => {161 c.header('Cache-Control', 'Max-Age=3600')162 return c.text('cached')163 })164Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 165–283why, one step back165 app.use('/vary1/*', cache({ cacheName: 'my-app-v1', wait: true, vary: ['Accept'] }))166 app.get('/vary1/', (c) => {167 return c.text('cached')168 })169170 app.use('/vary2/*', cache({ cacheName: 'my-app-v1', wait: true, vary: ['Accept'] }))171 app.get('/vary2/', (c) => {172 c.header('Vary', 'Accept-Encoding')173 return c.text('cached')174 })175176 app.use(177 '/vary3/*',178 cache({ cacheName: 'my-app-v1', wait: true, vary: ['Accept', 'Accept-Encoding'] })179 )180 app.get('/vary3/', (c) => {181 c.header('Vary', 'Accept-Language')182 return c.text('cached')183 })184185 app.use(186 '/vary4/*',187 cache({ cacheName: 'my-app-v1', wait: true, vary: ['Accept', 'Accept-Encoding'] })188 )189 app.get('/vary4/', (c) => {190 c.header('Vary', 'Accept, Accept-Language')191 return c.text('cached')192 })193194 app.use('/vary5/*', cache({ cacheName: 'my-app-v1', wait: true, vary: 'Accept' }))195 app.get('/vary5/', (c) => {196 return c.text('cached with Accept and Accept-Encoding headers')197 })198199 app.use(200 '/vary6/*',201 cache({ cacheName: 'my-app-v1', wait: true, vary: 'Accept, Accept-Encoding' })202 )203 app.get('/vary6/', (c) => {204 c.header('Vary', 'Accept, Accept-Language')205 return c.text('cached with Accept and Accept-Encoding headers as array')206 })207208 app.use('/vary7/*', cache({ cacheName: 'my-app-v1', wait: true, vary: ['Accept'] }))209 app.get('/vary7/', (c) => {210 c.header('Vary', '*')211 return c.text('cached')212 })213214 app.use('/default/*', cache({ cacheName: 'my-app-v1', wait: true, cacheControl: 'max-age=10' }))215 app.all('/default/:code/', (c) => {216 const code = parseInt(c.req.param('code'))217 // Intended to avoid the following error: `RangeError: init[“status”] must be in the range of 200 to 599, inclusive.`218 const res = {219 status: code,220 headers: new Headers(),221 clone: () => res,222 } as Response223 return res224 })225226 app.use(227 '/custom/*',228 cache({229 cacheName: 'my-app-v1',230 wait: true,231 cacheControl: 'max-age=10',232 cacheableStatusCodes: [200, 201],233 })234 )235 app.get('/custom/:code/', (c) => {236 const code = parseInt(c.req.param('code'))237 // Intended to avoid the following error: `RangeError: init[“status”] must be in the range of 200 to 599, inclusive.`238 const res = {239 status: code,240 headers: new Headers(),241 clone: () => res,242 } as Response243 return res244 })245246 const ctx = new Context()247248 it('Should return cached response', async () => {249 await app.request('http://localhost/wait/')250 const res = await app.request('http://localhost/wait/')251 expect(res).not.toBeNull()252 expect(res.status).toBe(200)253 expect(res.headers.get('cache-control')).toBe('max-age=10')254 expect(res.headers.get('x-count')).toBe('1')255 })256257 it('Should not return cached response', async () => {258 await app.fetch(new Request('http://localhost/not-wait/'), undefined, ctx)259 const res = await app.fetch(new Request('http://localhost/not-wait/'), undefined, ctx)260 expect(res).not.toBeNull()261 expect(res.status).toBe(200)262 expect(res.headers.get('cache-control')).toBe('max-age=10')263 })264265 it('Should not return duplicate header values', async () => {266 const res = await app.request('/wait2/')267 expect(res).not.toBeNull()268 expect(res.status).toBe(200)269 expect(res.headers.get('cache-control')).toBe('max-age=20')270 })271272 it('Should return composed middleware header values', async () => {273 const res = await app.request('/wait3/private/')274 expect(res).not.toBeNull()275 expect(res.status).toBe(200)276 expect(res.headers.get('cache-control')).toBe('private, max-age=10')277 })278279 it('Should return composed handler header values', async () => {280 const res = await app.request('/wait4/')281 expect(res).not.toBeNull()282 expect(res.status).toBe(200)283 expect(res.headers.get('cache-control')).toBe('private, max-age=10')fix(cache): deduplicate Cache-Control directives case-insensitively (#5025)nyxst4ckbefore adoptiona48c8bf
lines 284–292why, one step back284 })285286 it('Should not duplicate a Cache-Control directive that differs only in case', async () => {287 const res = await app.request('/wait5/')288 expect(res).not.toBeNull()289 expect(res.status).toBe(200)290 // Directive names are case-insensitive (RFC 7234 §5.2); the handler's291 // `Max-Age` must suppress the middleware's configured `max-age`.292 expect(res.headers.get('cache-control')).toBe('Max-Age=3600')Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 293–409why, one step back293 })294295 it('Should correctly apply a single Vary header from middleware', async () => {296 const res = await app.request('http://localhost/vary1/')297 expect(res).not.toBeNull()298 expect(res.status).toBe(200)299 expect(res.headers.get('vary')).toBe('accept')300 })301302 it('Should merge Vary headers from middleware and handler without duplicating', async () => {303 const res = await app.request('http://localhost/vary2/')304 expect(res).not.toBeNull()305 expect(res.status).toBe(200)306 expect(res.headers.get('vary')).toBe('accept, accept-encoding')307 })308309 it('Should deduplicate while merging multiple Vary headers from middleware and handler', async () => {310 const res = await app.request('http://localhost/vary3/')311 expect(res.headers.get('vary')).toBe('accept, accept-encoding, accept-language')312 })313314 it('Should prevent duplication of Vary headers when identical ones are set by both middleware and handler', async () => {315 const res = await app.request('http://localhost/vary4/')316 expect(res.headers.get('vary')).toBe('accept, accept-encoding, accept-language')317 })318319 it('Should correctly apply and return a single Vary header with Accept specified by middleware', async () => {320 const res = await app.request('http://localhost/vary5/')321 expect(res).not.toBeNull()322 expect(res.status).toBe(200)323 expect(res.headers.get('vary')).toBe('accept')324 })325326 it('Should merge Vary headers specified by middleware as a string with additional headers added by handler', async () => {327 const res = await app.request('http://localhost/vary6/')328 expect(res).not.toBeNull()329 expect(res.status).toBe(200)330 expect(res.headers.get('vary')).toBe('accept, accept-encoding, accept-language')331 })332333 it('Should prioritize the "*" Vary header from handler over any set by middleware', async () => {334 const res = await app.request('http://localhost/vary7/')335 expect(res).not.toBeNull()336 expect(res.status).toBe(200)337 expect(res.headers.get('vary')).toBe('*')338 })339340 it('Should not allow "*" as a Vary header in middleware configuration due to its impact on caching effectiveness', async () => {341 expect(() => cache({ cacheName: 'my-app-v1', wait: true, vary: ['*'] })).toThrow()342 expect(() => cache({ cacheName: 'my-app-v1', wait: true, vary: '*' })).toThrow()343 })344345 it.each([200])('Should cache %i in default cacheable status codes', async (code) => {346 await app.request(`http://localhost/default/${code}/`)347 const res = await app.request(`http://localhost/default/${code}/`)348 expect(res).not.toBeNull()349 expect(res.status).toBe(code)350 expect(res.headers.get('cache-control')).toBe('max-age=10')351 })352353 it.each([354 100, 101, 102, 103, 201, 202, 205, 207, 208, 226, 302, 303, 304, 307, 308, 400, 401, 402, 403,355 406, 407, 408, 409, 411, 412, 413, 415, 416, 417, 418, 421, 422, 423, 424, 425, 426, 428, 429,356 431, 451, 500, 502, 503, 504, 505, 506, 507, 508, 510, 511,357 ])('Should not cache %i in default cacheable status codes', async (code) => {358 await app.request(`http://localhost/default/${code}/`)359 const res = await app.request(`http://localhost/default/${code}/`)360 expect(res).not.toBeNull()361 expect(res.status).toBe(code)362 expect(res.headers.get('cache-control')).not.toBe('max-age=10')363 })364365 it.each([200, 201])('Should cache %i in custom cacheable status codes', async (code) => {366 await app.request(`http://localhost/custom/${code}/`)367 const res = await app.request(`http://localhost/custom/${code}/`)368 expect(res).not.toBeNull()369 expect(res.status).toBe(code)370 expect(res.headers.get('cache-control')).toBe('max-age=10')371 })372373 it.each([374 100, 101, 102, 103, 202, 205, 207, 208, 226, 302, 303, 304, 307, 308, 400, 401, 402, 403, 406,375 407, 408, 409, 411, 412, 413, 415, 416, 417, 418, 421, 422, 423, 424, 425, 426, 428, 429, 431,376 451, 500, 502, 503, 504, 505, 506, 507, 508, 510, 511,377 ])('Should not cache %i in custom cacheable status codes', async (code) => {378 await app.request(`http://localhost/custom/${code}/`)379 const res = await app.request(`http://localhost/custom/${code}/`)380 expect(res).not.toBeNull()381 expect(res.status).toBe(code)382 expect(res.headers.get('cache-control')).not.toBe('max-age=10')383 })384385 it('Should not be enabled if caches is not defined', async () => {386 vi.stubGlobal('caches', undefined)387 const app = new Hono()388 app.use(cache({ cacheName: 'my-app-v1', cacheControl: 'max-age=10' }))389 app.get('/', (c) => {390 return c.text('cached')391 })392 expect(caches).toBeUndefined()393 const res = await app.request('/')394 expect(res).not.toBeNull()395 expect(res.status).toBe(200)396 expect(res.headers.get('cache-control')).toBe(null)397 })398399 it('Should call onCacheNotAvailable when caches is not defined', async () => {400 vi.stubGlobal('caches', undefined)401 const spy = vi.fn()402 const app = new Hono()403 app.use(cache({ cacheName: 'my-app-v1', onCacheNotAvailable: spy }))404 app.get('/', (c) => {405 return c.text('cached')406 })407 const res = await app.request('/')408 expect(res.status).toBe(200)409 expect(spy).toHaveBeenCalledOnce()Merge pull request #5154 from honojs/nextYusuke Wadabefore adoptionb0c2d90
lines 410–412why, one step back410 expect(spy).toHaveBeenCalledWith(411 'Cache Middleware is not enabled because caches is not defined.'412 )Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 413–746why, one step back413 vi.unstubAllGlobals()414 })415416 it('Should suppress default log when onCacheNotAvailable is false', async () => {417 vi.stubGlobal('caches', undefined)418 const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {})419 const app = new Hono()420 app.use(cache({ cacheName: 'my-app-v1', onCacheNotAvailable: false }))421 app.get('/', (c) => {422 return c.text('cached')423 })424 const res = await app.request('/')425 expect(res.status).toBe(200)426 expect(logSpy).not.toHaveBeenCalledWith(427 'Cache Middleware is not enabled because caches is not defined.'428 )429 logSpy.mockRestore()430 vi.unstubAllGlobals()431 })432})433434describe('Cache Skipping Logic', () => {435 const stubStoreBackedCache = () => {436 const store = new Map<string | Request, Response>()437 const mockCache = {438 match: vi.fn((key: string | Request) => Promise.resolve(store.get(key)?.clone())),439 put: vi.fn((key: string | Request, response: Response) => {440 store.set(key, response.clone())441 return Promise.resolve()442 }),443 keys: vi.fn(() => Promise.resolve(Array.from(store.keys()))),444 }445446 vi.stubGlobal('caches', {447 open: vi.fn().mockResolvedValue(mockCache),448 })449450 return { mockCache }451 }452453 let putSpy: ReturnType<typeof vi.fn>454 let matchSpy: ReturnType<typeof vi.fn>455456 beforeEach(() => {457 matchSpy = vi.fn().mockResolvedValue(undefined)458 putSpy = vi.fn()459 const mockCache = {460 match: matchSpy, // Always miss unless a test overrides it461 put: putSpy, // We spy on this462 keys: vi.fn().mockResolvedValue([]),463 }464465 vi.stubGlobal('caches', {466 open: vi.fn().mockResolvedValue(mockCache),467 })468 })469470 afterEach(() => {471 vi.restoreAllMocks()472 })473474 it('Should NOT cache response if Cache-Control contains "private"', async () => {475 const app = new Hono()476 app.use('*', cache({ cacheName: 'skip-test', wait: true }))477 app.get('/', (c) => {478 c.header('Cache-Control', 'private, max-age=3600')479 return c.text('response')480 })481482 const res = await app.request('/')483 expect(res.status).toBe(200)484 // IMPORTANT: put() should NOT be called485 expect(putSpy).not.toHaveBeenCalled()486 })487488 it('Should NOT cache response if Cache-Control contains "no-store"', async () => {489 const app = new Hono()490 app.use('*', cache({ cacheName: 'skip-test', wait: true }))491 app.get('/', (c) => {492 c.header('Cache-Control', 'no-store')493 return c.text('response')494 })495496 await app.request('/')497 expect(putSpy).not.toHaveBeenCalled()498 })499500 it('Should NOT cache response if Cache-Control contains no-cache="Set-Cookie"', async () => {501 const app = new Hono()502 app.use('*', cache({ cacheName: 'skip-test', wait: true }))503 app.get('/', (c) => {504 c.header('Cache-Control', 'no-cache="Set-Cookie"')505 return c.text('response')506 })507508 await app.request('/')509 expect(putSpy).not.toHaveBeenCalled()510 })511512 it('Should NOT cache response if Set-Cookie header is present', async () => {513 const app = new Hono()514 app.use('*', cache({ cacheName: 'skip-test', wait: true }))515 app.get('/', (c) => {516 c.header('Set-Cookie', 'session=secret')517 return c.text('response')518 })519520 await app.request('/')521 expect(putSpy).not.toHaveBeenCalled()522 })523524 it('Should cache normal responses (Control Test)', async () => {525 const app = new Hono()526 app.use('*', cache({ cacheName: 'skip-test', wait: true }))527 app.get('/', (c) => {528 return c.text('response')529 })530531 await app.request('/')532 // IMPORTANT: put() SHOULD be called for normal responses533 expect(putSpy).toHaveBeenCalled()534 })535536 it.each(['Accept-Language', 'Authorization', 'X-Tenant'])(537 'Should NOT cache response if Vary: %s is set',538 async (vary) => {539 const app = new Hono()540 app.use('*', cache({ cacheName: 'skip-test', wait: true }))541 app.get('/', (c) => {542 c.header('Vary', vary)543 return c.text('response')544 })545546 await app.request('/')547 expect(putSpy).not.toHaveBeenCalled()548 }549 )550551 it('Should set configured Vary header and cache by the configured request header value', async () => {552 const { mockCache } = stubStoreBackedCache()553 const app = new Hono()554 let count = 0555 app.use('*', cache({ cacheName: 'skip-test', wait: true, vary: 'Accept' }))556 app.get('/', (c) => {557 count++558 c.header('X-Count', `${count}`)559 return c.text('response')560 })561562 await app.request('/')563 const res = await app.request('/')564 expect(res.headers.get('Vary')).toBe('accept')565 expect(res.headers.get('X-Count')).toBe('1')566 expect(mockCache.put).toHaveBeenCalledOnce()567 })568569 it('Should store separate variants for different Accept-Language request values', async () => {570 const { mockCache } = stubStoreBackedCache()571 const app = new Hono()572 let count = 0573 app.use('*', cache({ cacheName: 'vary-language-test', wait: true, vary: 'Accept-Language' }))574 app.get('/', (c) => {575 count++576 c.header('X-Count', `${count}`)577 return c.text(c.req.header('Accept-Language') ?? 'missing')578 })579580 await app.request('/', {581 headers: {582 'Accept-Language': 'en',583 },584 })585 const en = await app.request('/', {586 headers: {587 'Accept-Language': 'en',588 },589 })590 await app.request('/', {591 headers: {592 'Accept-Language': 'ja',593 },594 })595 const ja = await app.request('/', {596 headers: {597 'Accept-Language': 'ja',598 },599 })600601 expect(await en.text()).toBe('en')602 expect(en.headers.get('X-Count')).toBe('1')603 expect(await ja.text()).toBe('ja')604 expect(ja.headers.get('X-Count')).toBe('2')605 expect(mockCache.put).toHaveBeenCalledTimes(2)606 })607608 it('Should keep missing and present Vary request header values in separate variants', async () => {609 stubStoreBackedCache()610 const app = new Hono()611 let count = 0612 app.use('*', cache({ cacheName: 'vary-missing-test', wait: true, vary: 'Accept-Language' }))613 app.get('/', (c) => {614 count++615 c.header('X-Count', `${count}`)616 return c.text(c.req.header('Accept-Language') ?? 'missing')617 })618619 await app.request('/')620 await app.request('/', {621 headers: {622 'Accept-Language': 'en',623 },624 })625 const missing = await app.request('/')626 const present = await app.request('/', {627 headers: {628 'Accept-Language': 'en',629 },630 })631632 expect(await missing.text()).toBe('missing')633 expect(missing.headers.get('X-Count')).toBe('1')634 expect(await present.text()).toBe('en')635 expect(present.headers.get('X-Count')).toBe('2')636 })637638 it('Should store separate variants using multiple configured request headers', async () => {639 const { mockCache } = stubStoreBackedCache()640 const app = new Hono()641 let count = 0642 app.use(643 '*',644 cache({ cacheName: 'vary-multiple-test', wait: true, vary: ['Accept', 'Accept-Encoding'] })645 )646 app.get('/', (c) => {647 count++648 c.header('X-Count', `${count}`)649 return c.text(`${c.req.header('Accept')}:${c.req.header('Accept-Encoding')}`)650 })651652 await app.request('/', {653 headers: {654 Accept: 'text/plain',655 'Accept-Encoding': 'gzip',656 },657 })658 const same = await app.request('/', {659 headers: {660 Accept: 'text/plain',661 'Accept-Encoding': 'gzip',662 },663 })664 await app.request('/', {665 headers: {666 Accept: 'application/json',667 'Accept-Encoding': 'gzip',668 },669 })670 const differentAccept = await app.request('/', {671 headers: {672 Accept: 'application/json',673 'Accept-Encoding': 'gzip',674 },675 })676 await app.request('/', {677 headers: {678 Accept: 'text/plain',679 'Accept-Encoding': 'br',680 },681 })682 const differentEncoding = await app.request('/', {683 headers: {684 Accept: 'text/plain',685 'Accept-Encoding': 'br',686 },687 })688689 expect(same.headers.get('X-Count')).toBe('1')690 expect(differentAccept.headers.get('X-Count')).toBe('2')691 expect(differentEncoding.headers.get('X-Count')).toBe('3')692 expect(mockCache.put).toHaveBeenCalledTimes(3)693 })694695 it('Should store when the handler Vary header is covered by configured Vary headers', async () => {696 const { mockCache } = stubStoreBackedCache()697 const app = new Hono()698 app.use('*', cache({ cacheName: 'vary-covered-test', wait: true, vary: 'Accept-Language' }))699 app.get('/', (c) => {700 c.header('Vary', 'Accept-Language')701 return c.text('response')702 })703704 await app.request('/')705 expect(mockCache.put).toHaveBeenCalledOnce()706 })707708 it('Should not store when the handler adds Vary headers not covered by configured Vary headers', async () => {709 const app = new Hono()710 app.use('*', cache({ cacheName: 'skip-test', wait: true, vary: 'Accept-Language' }))711 app.get('/', (c) => {712 c.header('Vary', 'Accept-Language, Cookie')713 return c.text('response')714 })715716 await app.request('/')717 expect(putSpy).not.toHaveBeenCalled()718 })719720 it('Should not store Vary: * responses even when Vary headers are configured', async () => {721 const app = new Hono()722 app.use('*', cache({ cacheName: 'skip-test', wait: true, vary: 'Accept-Language' }))723 app.get('/', (c) => {724 c.header('Vary', '*')725 return c.text('response')726 })727728 await app.request('/')729 expect(putSpy).not.toHaveBeenCalled()730 })731732 it('Should bypass cache for Authorization requests', async () => {733 const app = new Hono()734 app.use('*', cache({ cacheName: 'skip-test', wait: true, cacheControl: 'max-age=10' }))735 app.get('/', (c) => {736 return c.text('fresh')737 })738739 const res = await app.request('/', {740 headers: {741 Authorization: 'Bearer token',742 },743 })744 expect(await res.text()).toBe('fresh')745 expect(caches.open).not.toHaveBeenCalled()746 expect(putSpy).not.toHaveBeenCalled()Merge pull request #5154 from honojs/nextYusuke Wadabefore adoptionb0c2d90
lines 747–748why, one step back747 })748Merge commit from forkTaku Amanobefore adoption9c28d72
lines 749–767why, one step back749 it('Should cache request URLs containing a fragment', async () => {750 const { mockCache } = stubStoreBackedCache()751 const app = new Hono()752 let requestCount = 0753 app.use('*', cache({ cacheName: 'fragment-request-test', wait: true }))754 app.get('/', (c) => {755 requestCount++756 return c.text(c.req.query('name') ?? 'default')757 })758759 expect(await (await app.request('http://localhost/#?name=probe')).text()).toBe('default')760 expect(await (await app.request('http://localhost/#?name=probe')).text()).toBe('default')761 expect(requestCount).toBe(1)762 expect(mockCache.put).toHaveBeenCalledOnce()763 expect(mockCache.put.mock.calls[0][0]).toBe(764 'http://localhost/.hono/cache?__hono_cache_key=http%3A%2F%2Flocalhost%2F%23%3Fname%3Dprobe&__hono_cache_method=GET'765 )766 })767Merge pull request #5154 from honojs/nextYusuke Wadabefore adoptionb0c2d90
lines 768–966why, one step back768 it('Should cache QUERY responses without consuming the handler request body', async () => {769 const { mockCache } = stubStoreBackedCache()770 const app = new Hono()771 let queryCount = 0772 app.use('*', cache({ cacheName: 'query-test', wait: true, cacheControl: 'max-age=10' }))773 app.on('QUERY', '/resource', async (c) => {774 queryCount++775 c.header('X-Count', `${queryCount}`)776 return c.text(await c.req.raw.text())777 })778779 const request = () =>780 app.request('/resource', {781 method: 'QUERY',782 headers: { 'Content-Type': 'application/json' },783 body: '{"query":"hono"}',784 })785786 await request()787 const res = await request()788789 expect(await res.text()).toBe('{"query":"hono"}')790 expect(res.headers.get('X-Count')).toBe('1')791 expect(res.headers.get('Cache-Control')).toBe('max-age=10')792 expect(mockCache.put).toHaveBeenCalledOnce()793 })794795 it('Should bypass QUERY caching when the measured body exceeds the configured limit', async () => {796 const { mockCache } = stubStoreBackedCache()797 const app = new Hono()798 let queryCount = 0799 app.use('*', cache({ cacheName: 'query-body-limit-test', wait: true, maxQueryBodySize: 4 }))800 app.on('QUERY', '/resource', async (c) => {801 queryCount++802 c.header('X-Count', `${queryCount}`)803 return c.text(await c.req.text())804 })805806 const request = () => {807 const body = new ReadableStream({808 start(controller) {809 controller.enqueue(new TextEncoder().encode('ab'))810 controller.enqueue(new TextEncoder().encode('cde'))811 controller.close()812 },813 })814 return app.request('/resource', {815 method: 'QUERY',816 headers: {817 'Content-Length': '1',818 'Content-Type': 'text/plain',819 },820 body,821 duplex: 'half',822 } as RequestInit & { duplex: 'half' })823 }824825 await request()826 const res = await request()827828 expect(await res.text()).toBe('abcde')829 expect(res.headers.get('X-Count')).toBe('2')830 expect(caches.open).not.toHaveBeenCalled()831 expect(mockCache.put).not.toHaveBeenCalled()832 })833834 it('Should cache QUERY requests at the configured body size limit', async () => {835 const { mockCache } = stubStoreBackedCache()836 const app = new Hono()837 let queryCount = 0838 app.use(839 '*',840 cache({ cacheName: 'query-body-limit-boundary-test', wait: true, maxQueryBodySize: 4 })841 )842 app.on('QUERY', '/resource', async (c) => {843 queryCount++844 c.header('X-Count', `${queryCount}`)845 return c.text(await c.req.text())846 })847848 const request = () =>849 app.request('/resource', {850 method: 'QUERY',851 headers: { 'Content-Type': 'text/plain' },852 body: 'abcd',853 })854855 await request()856 const res = await request()857858 expect(await res.text()).toBe('abcd')859 expect(res.headers.get('X-Count')).toBe('1')860 expect(mockCache.put).toHaveBeenCalledOnce()861 })862863 it('Should keep QUERY request content and Content-Type in separate cache variants', async () => {864 const { mockCache } = stubStoreBackedCache()865 const app = new Hono()866 let queryCount = 0867 app.use(868 '*',869 cache({ cacheName: 'query-variant-test', wait: true, keyGenerator: () => 'query-key' })870 )871 app.on('QUERY', '/resource', async (c) => {872 queryCount++873 c.header('X-Count', `${queryCount}`)874 return c.text(`${c.req.header('Content-Type')}:${await c.req.text()}`)875 })876877 const request = (body: string, contentType: string) =>878 app.request('/resource', {879 method: 'QUERY',880 headers: { 'Content-Type': contentType },881 body,882 })883884 await request('one', 'text/plain')885 const same = await request('one', 'text/plain')886 await request('two', 'text/plain')887 const differentContent = await request('two', 'text/plain')888 await request('one', 'application/json')889 const differentContentType = await request('one', 'application/json')890891 expect(same.headers.get('X-Count')).toBe('1')892 expect(differentContent.headers.get('X-Count')).toBe('2')893 expect(differentContentType.headers.get('X-Count')).toBe('3')894 expect(mockCache.put).toHaveBeenCalledTimes(3)895 })896897 it('Should keep GET and QUERY responses in separate cache entries', async () => {898 const { mockCache } = stubStoreBackedCache()899 const app = new Hono()900 app.use('*', cache({ cacheName: 'method-test', wait: true }))901 app.get('/resource', (c) => c.text('get response'))902 app.on('QUERY', '/resource', (c) => c.text('query response'))903904 await app.request('/resource')905 await app.request('/resource', {906 method: 'QUERY',907 headers: { 'Content-Type': 'application/json' },908 body: '{}',909 })910 const getRes = await app.request('/resource')911 const queryRes = await app.request('/resource', {912 method: 'QUERY',913 headers: { 'Content-Type': 'application/json' },914 body: '{}',915 })916917 expect(await getRes.text()).toBe('get response')918 expect(await queryRes.text()).toBe('query response')919 expect(mockCache.put).toHaveBeenCalledTimes(2)920 })921922 it('Should not let a GET URL alias an internally generated QUERY cache key', async () => {923 const { mockCache } = stubStoreBackedCache()924 const app = new Hono()925 app.use('*', cache({ cacheName: 'method-collision-test', wait: true }))926 app.get('/resource', (c) => c.text('get response'))927 app.get('*', (c) => c.text('get response'))928 app.on('QUERY', '/resource', (c) => c.text('query response'))929930 await app.request('/resource', {931 method: 'QUERY',932 headers: { 'Content-Type': 'application/json' },933 body: '{}',934 })935936 const queryKey = mockCache.put.mock.calls[0][0] as string937 const getRes = await app.request(queryKey)938 const queryRes = await app.request('/resource', {939 method: 'QUERY',940 headers: { 'Content-Type': 'application/json' },941 body: '{}',942 })943944 expect(await getRes.text()).toBe('get response')945 expect(await queryRes.text()).toBe('query response')946 expect(mockCache.put).toHaveBeenCalledTimes(2)947 })948949 it('Should not resolve a custom cache key as a request URL', async () => {950 const { mockCache } = stubStoreBackedCache()951 const app = new Hono()952 app.use(953 '/resource',954 cache({955 cacheName: 'custom-key-collision-test',956 wait: true,957 keyGenerator: () => 'query-key',958 })959 )960 app.use('/query-key', cache({ cacheName: 'custom-key-collision-test', wait: true }))961 app.get('/resource', (c) => c.text('custom key response'))962 app.get('/query-key', (c) => c.text('request URL response'))963964 expect(await (await app.request('/resource')).text()).toBe('custom key response')965 expect(await (await app.request('/query-key')).text()).toBe('request URL response')966 expect(mockCache.put).toHaveBeenCalledTimes(2)Merge commit from forkTaku Amanobefore adoption9c28d72
lines 967–997why, one step back967 })968969 it('Should preserve fragments in custom cache keys', async () => {970 const { mockCache } = stubStoreBackedCache()971 const app = new Hono()972 let requestCount = 0973 app.use(974 '/report',975 cache({976 cacheName: 'custom-fragment-key-test',977 wait: true,978 keyGenerator: (c) => `${c.req.path}#${c.req.header('X-Tenant-Id')}`,979 })980 )981 app.get('/report', (c) => {982 requestCount++983 return c.text(`report for ${c.req.header('X-Tenant-Id')}`)984 })985986 const request = (tenant: string) =>987 app.request('/report', { headers: { 'X-Tenant-Id': tenant } })988989 expect(await (await request('acme')).text()).toBe('report for acme')990 expect(await (await request('globex')).text()).toBe('report for globex')991 expect(await (await request('acme')).text()).toBe('report for acme')992 expect(requestCount).toBe(2)993 expect(mockCache.put).toHaveBeenCalledTimes(2)994 expect(mockCache.put.mock.calls.map(([key]) => key)).toEqual([995 'http://localhost/.hono/cache?__hono_cache_key=%2Freport%23acme&__hono_cache_method=GET',996 'http://localhost/.hono/cache?__hono_cache_key=%2Freport%23globex&__hono_cache_method=GET',997 ])Merge pull request #5154 from honojs/nextYusuke Wadabefore adoptionb0c2d90
lines 998–1184why, one step back998 })9991000 it('Should keep QUERY digest and vary values with a fragmented custom cache key', async () => {1001 const { mockCache } = stubStoreBackedCache()1002 const app = new Hono()1003 let queryCount = 01004 app.use(1005 '*',1006 cache({1007 cacheName: 'query-fragment-test',1008 wait: true,1009 vary: 'X-Variant',1010 keyGenerator: (c) => `${c.req.url}#custom-fragment`,1011 })1012 )1013 app.on('QUERY', '/resource', async (c) => {1014 queryCount++1015 return c.text(`${await c.req.text()}:${c.req.header('X-Variant')}`)1016 })10171018 const request = (body: string, variant: string) =>1019 app.request('/resource', {1020 method: 'QUERY',1021 headers: { 'Content-Type': 'text/plain', 'X-Variant': variant },1022 body,1023 })10241025 expect(await (await request('one', 'a')).text()).toBe('one:a')1026 expect(await (await request('two', 'a')).text()).toBe('two:a')1027 expect(await (await request('one', 'b')).text()).toBe('one:b')1028 expect(await (await request('one', 'a')).text()).toBe('one:a')1029 expect(queryCount).toBe(3)1030 expect(mockCache.put).toHaveBeenCalledTimes(3)1031 })10321033 it('Should bypass QUERY caching when Web Crypto is not available', async () => {1034 const originalCrypto = globalThis.crypto1035 vi.stubGlobal('crypto', undefined)10361037 try {1038 const { mockCache } = stubStoreBackedCache()1039 const app = new Hono()1040 let queryCount = 01041 let getCount = 01042 const onCacheNotAvailable = vi.fn()1043 app.use(1044 '*',1045 cache({1046 cacheName: 'query-no-crypto-test',1047 wait: true,1048 onCacheNotAvailable,1049 })1050 )1051 app.get('/resource', (c) => {1052 getCount++1053 c.header('X-Count', `${getCount}`)1054 return c.text('get response')1055 })1056 app.on('QUERY', '/resource', (c) => {1057 queryCount++1058 c.header('X-Count', `${queryCount}`)1059 return c.text('query response')1060 })10611062 expect(onCacheNotAvailable).toHaveBeenCalledOnce()1063 expect(onCacheNotAvailable).toHaveBeenCalledWith(1064 'Cache Middleware cannot cache QUERY requests because Web Crypto is not available.'1065 )10661067 const request = () =>1068 app.request('/resource', {1069 method: 'QUERY',1070 headers: { 'Content-Type': 'application/json' },1071 body: '{}',1072 })10731074 await request()1075 const res = await request()10761077 expect(res.headers.get('X-Count')).toBe('2')1078 expect(caches.open).not.toHaveBeenCalled()1079 expect(onCacheNotAvailable).toHaveBeenCalledOnce()10801081 await app.request('/resource')1082 const getRes = await app.request('/resource')10831084 expect(getRes.headers.get('X-Count')).toBe('1')1085 expect(mockCache.put).toHaveBeenCalledOnce()1086 } finally {1087 vi.stubGlobal('crypto', originalCrypto)1088 }1089 })10901091 it('Should bypass QUERY caching when the request content cannot be read', async () => {1092 const app = new Hono()1093 let queryCount = 01094 app.use('*', async (c, next) => {1095 await c.req.raw.text()1096 await next()1097 })1098 app.use('*', cache({ cacheName: 'query-consumed-body-test', wait: true }))1099 app.on('QUERY', '/resource', (c) => {1100 queryCount++1101 c.header('X-Count', `${queryCount}`)1102 return c.text('query response')1103 })11041105 const request = () =>1106 app.request('/resource', {1107 method: 'QUERY',1108 headers: { 'Content-Type': 'application/json' },1109 body: '{}',1110 })11111112 await request()1113 const res = await request()11141115 expect(res.headers.get('X-Count')).toBe('2')1116 expect(caches.open).not.toHaveBeenCalled()1117 })11181119 it('Should bypass QUERY caching after the body was read directly as FormData', async () => {1120 const { mockCache } = stubStoreBackedCache()1121 const app = new Hono()1122 let queryCount = 01123 app.use('*', async (c, next) => {1124 expect((await c.req.formData()).get('query')).toBe('hono')1125 await next()1126 })1127 app.use('*', cache({ cacheName: 'query-cached-form-data-test', wait: true }))1128 app.on('QUERY', '/resource', (c) => {1129 queryCount++1130 c.header('X-Count', `${queryCount}`)1131 return c.text('query response')1132 })11331134 const body = [1135 '--hono-boundary',1136 'Content-Disposition: form-data; name="query"',1137 '',1138 'hono',1139 '--hono-boundary--',1140 '',1141 ].join('\r\n')1142 const request = () =>1143 app.request('/resource', {1144 method: 'QUERY',1145 headers: { 'Content-Type': 'multipart/form-data; boundary=hono-boundary' },1146 body,1147 })11481149 await request()1150 const res = await request()11511152 expect(res.headers.get('X-Count')).toBe('2')1153 expect(caches.open).not.toHaveBeenCalled()1154 expect(mockCache.put).not.toHaveBeenCalled()1155 })11561157 it('Should cache QUERY after the body was read through HonoRequest', async () => {1158 const { mockCache } = stubStoreBackedCache()1159 const app = new Hono()1160 let queryCount = 01161 app.use('*', async (c, next) => {1162 expect(await c.req.text()).toBe('{}')1163 await next()1164 })1165 app.use('*', cache({ cacheName: 'query-cached-body-test', wait: true }))1166 app.on('QUERY', '/resource', async (c) => {1167 queryCount++1168 c.header('X-Count', `${queryCount}`)1169 return c.text(await c.req.text())1170 })11711172 const request = () =>1173 app.request('/resource', {1174 method: 'QUERY',1175 headers: { 'Content-Type': 'application/json' },1176 body: '{}',1177 })11781179 await request()1180 const res = await request()11811182 expect(await res.text()).toBe('{}')1183 expect(res.headers.get('X-Count')).toBe('1')1184 expect(mockCache.put).toHaveBeenCalledOnce()Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 1185–1211why, one step back1185 })11861187 it('Should not use or store cache for POST requests', async () => {1188 const app = new Hono()1189 let postCount = 01190 app.use('*', cache({ cacheName: 'skip-test', wait: true, cacheControl: 'max-age=10' }))1191 app.get('/resource', (c) => {1192 return c.text('get response')1193 })1194 app.post('/resource', (c) => {1195 postCount++1196 c.header('X-Count', `${postCount}`)1197 return c.text('post response')1198 })11991200 await app.request('/resource')1201 putSpy.mockClear()1202 matchSpy.mockClear()12031204 await app.request('/resource', { method: 'POST' })1205 const res = await app.request('/resource', { method: 'POST' })1206 expect(res.headers.get('X-Count')).toBe('2')1207 expect(res.headers.get('Cache-Control')).toBeNull()1208 expect(matchSpy).not.toHaveBeenCalled()1209 expect(putSpy).not.toHaveBeenCalled()1210 })1211})