(event)
| 18 | }) |
| 19 | |
| 20 | async function handleRequest(event) { |
| 21 | const request = event.request |
| 22 | |
| 23 | // Only GET requests work with this proxy. |
| 24 | if (request.method !== 'GET') return MethodNotAllowed(request) |
| 25 | |
| 26 | // https://developers.cloudflare.com/workers/examples/cache-api |
| 27 | const cacheURL = new URL(request.url); |
| 28 | |
| 29 | const cacheKey = new Request(cacheURL.toString(), request); |
| 30 | const cache = caches.default |
| 31 | |
| 32 | let response = await cache.match(cacheKey); |
| 33 | |
| 34 | if (!response) { |
| 35 | // If not in cache, get it from origin |
| 36 | response = await fetch(GTM_URL); |
| 37 | |
| 38 | // Must use Response constructor to inherit all of response's fields |
| 39 | response = new Response(response.body, response) |
| 40 | |
| 41 | response.headers.append("Cache-Control", `s-maxage=${CACHE_EXPIRY}`) |
| 42 | |
| 43 | // Store the fetched response as cacheKey |
| 44 | // Use waitUntil so you can return the response without blocking on |
| 45 | // writing to cache |
| 46 | event.waitUntil(cache.put(cacheKey, response.clone())) |
| 47 | } |
| 48 | |
| 49 | return response |
| 50 | } |
| 51 | |
| 52 | // Use the following when the request is not a valid GET request |
| 53 | function MethodNotAllowed(request) { |
no test coverage detected