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;