Caching R2 using worker cache api
Hello I was going through the docs and saw we can cache r2 resource through workers using the cache api.
I have tried to implement. It's working fine in local developement. I am getting CF-Cache-Status in local but when I am deploying I am not seeing any Cache Status header with the worker domain.
Here's the code
I have tried to implement. It's working fine in local developement. I am getting CF-Cache-Status in local but when I am deploying I am not seeing any Cache Status header with the worker domain.
Here's the code
const handler: ExportedHandler = {
async fetch(request, env, ctx) {
const cacheUrl = new URL(request.url);
const cacheKey = new Request(cacheUrl.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 origin, and store it in the cache
let response = await cache.match(cacheKey);
if (!response) {
console.log(`Response for request url: ${request.url} not present in cache. Fetching and caching request.`);
const url = new URL(request.url);
// If not in cache, get it from origin
response = await fetch(`https://pub-92d2c9da4.....r2.dev${url.pathname}`, {
cf: {
cacheTtl: 500,
cacheEverything: true,
},
});
response = new Response(response.body, response);
response.headers.append('Cache-Control', 's-maxage=500');
response.headers.append('Cache-Control', 'max-age=86400');
response.headers.append('Cache-Control', 'public');
ctx.waitUntil(cache.put(cacheKey, response.clone()));
} else {
console.log(`Cache hit for: ${request.url}.`);
}
return response;
},
};
export default handler;const handler: ExportedHandler = {
async fetch(request, env, ctx) {
const cacheUrl = new URL(request.url);
const cacheKey = new Request(cacheUrl.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 origin, and store it in the cache
let response = await cache.match(cacheKey);
if (!response) {
console.log(`Response for request url: ${request.url} not present in cache. Fetching and caching request.`);
const url = new URL(request.url);
// If not in cache, get it from origin
response = await fetch(`https://pub-92d2c9da4.....r2.dev${url.pathname}`, {
cf: {
cacheTtl: 500,
cacheEverything: true,
},
});
response = new Response(response.body, response);
response.headers.append('Cache-Control', 's-maxage=500');
response.headers.append('Cache-Control', 'max-age=86400');
response.headers.append('Cache-Control', 'public');
ctx.waitUntil(cache.put(cacheKey, response.clone()));
} else {
console.log(`Cache hit for: ${request.url}.`);
}
return response;
},
};
export default handler;