Skip to content

Instantly share code, notes, and snippets.

@SegersIan
Last active December 25, 2018 12:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SegersIan/c5bfc5934ac0a41049ac882ebe1154f6 to your computer and use it in GitHub Desktop.
Save SegersIan/c5bfc5934ac0a41049ac882ebe1154f6 to your computer and use it in GitHub Desktop.
CloudFlareWebWorker PoC of the cache
addEventListener('fetch', event => {
event.respondWith(intercept(event.request));
});
async function intercept(request) {
// Define a "constant" key so I always would get the same response from my cache (just for PoC purpose).
const myRequest = 'http://www.myconstantvalue.com';
try{
const cache = getCache();
// Fetch request from cache
const response = await cache.match(myRequest, { ignoreMethod : true });
// If response found in cache, return
if(response){
return response;
}
// Response not yet in cache, let's define a new response with a header with long expire date
// This should ensure that we have a response cached for a long time (for this PoC)
const ops = {
headers : {
'Expires' : 'Wed Jan 01 2020 01:01:01 GMT'
};
const newResponse = new Response('Hello world from cache : ' + Date.now(), ops);
// Put new response in cache
await cache.put(myRequest, newResponse.clone());
// Return new response
return newResponse;
} catch(e){
console.error(e);
return new Response(e.message + ' - ' + e.stack);
}
}
function getCache(){
return caches.default;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment