Skip to content
File

Blob: src/workerd/api/tests/cache-mock.js

javascript49 lines
1// Copyright (c) 2017-2023 Cloudflare, Inc.
2// Licensed under the Apache 2.0 license found in the LICENSE file or at:
3// https://opensource.org/licenses/Apache-2.0
4 
5// Mock cache backend - responds to GET (match), PUT (put), and PURGE (delete)
6export default {
7 async fetch(request) {
8 const url = new URL(request.url);
9 const headers = new Headers();
10 
11 // Handle cache.match() operations (GET requests)
12 if (request.method === 'GET') {
13 // Check if this is a cache.match() request (has only-if-cached)
14 const cacheControl = request.headers.get('cache-control');
15 if (cacheControl?.includes('only-if-cached')) {
16 // Simulate cache HIT
17 if (url.pathname.includes('cached-resource')) {
18 headers.set('CF-Cache-Status', 'HIT');
19 return new Response('Cached content', { status: 200, headers });
20 }
21 // Simulate cache MISS
22 headers.set('CF-Cache-Status', 'MISS');
23 return new Response(null, { status: 504, headers });
24 }
25 }
26 
27 // Handle cache.put() operations (PUT requests)
28 if (request.method === 'PUT') {
29 // Read the body (which contains the serialized response to cache)
30 await request.text();
31 
32 // Simulate successful cache write
33 return new Response(null, { status: 204 });
34 }
35 
36 // Handle cache.delete() operations (PURGE requests)
37 if (request.method === 'PURGE') {
38 // Simulate successful deletion
39 if (url.pathname.includes('delete-exists')) {
40 return new Response(null, { status: 200 });
41 }
42 // Simulate not found
43 return new Response(null, { status: 404 });
44 }
45 
46 return new Response('Not Found', { status: 404 });
47 },
48};