Last active
January 10, 2023 09:22
-
-
Save teckl/03f250d82781c97f0fd2fad0bd59c620 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// see also https://developers.cloudflare.com/r2/examples/cache-api/ | |
export default { | |
async fetch(request, env, context) { | |
try { | |
const url = new URL(request.url); | |
// Construct the cache key from the cache URL | |
const cacheKey = new Request(url.toString(), request); | |
const cache = caches.default; | |
// Check whether the value is already available in the cache | |
// if not, you will need to fetch it from R2, and store it in the cache | |
// for future access | |
let response = await cache.match(cacheKey); | |
if (response) { | |
console.log(`Cache hit for: ${request.url}.`); | |
return response; | |
} | |
console.log( | |
`Response for request url: ${request.url} not present in cache. Fetching and caching request.` | |
); | |
// info -> i/in/info | |
const pathname = url.pathname; | |
const req_headers = request.headers; | |
const host = req_headers.get('Host'); | |
const subdomain = host.split('.')[0]; | |
const first = subdomain.slice(0,1); | |
const second = subdomain.slice(0,2); | |
const new_key = first + '/' + second + '/' + subdomain + url.pathname; | |
console.log(new_key); | |
// If not in cache, get it from R2 | |
//const objectKey = url.pathname.slice(1); | |
const object = await env.MY_BUCKET.get(new_key); | |
if (object === null) { | |
return new Response('Object Not Found', { status: 404 }); | |
} | |
// Set the appropriate object headers | |
const headers = new Headers(); | |
object.writeHttpMetadata(headers); | |
headers.set('etag', object.httpEtag); | |
// Cache API respects Cache-Control headers. Setting s-max-age to 10 | |
// will limit the response to be in cache for 10 seconds max | |
// Any changes made to the response here will be reflected in the cached value | |
headers.append('Cache-Control', 's-maxage=600'); | |
response = new Response(object.body, { | |
headers, | |
}); | |
// Store the fetched response as cacheKey | |
// Use waitUntil so you can return the response without blocking on | |
// writing to cache | |
context.waitUntil(cache.put(cacheKey, response.clone())); | |
return response; | |
} catch (e) { | |
return new Response('Error thrown ' + e.message); | |
} | |
}, | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment