Last active
December 25, 2018 12:30
-
-
Save SegersIan/c5bfc5934ac0a41049ac882ebe1154f6 to your computer and use it in GitHub Desktop.
CloudFlareWebWorker PoC of the cache
This file contains 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
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