Write a cache-first service worker handler.
The tea shop's service worker sends every request to the network, even for its hashed stylesheets and pictures, which never change. Write handleFetch(event), the service worker's fetch handler, so it answers cache first from the Cache Storage cache named "tea-shop-v1":
If the cache has a response for the request, answer with it and don't use the network. If it doesn't, fetch the request, answer with that response, and store a copy in the cache for next time, but only when the response is ok (a 404 or a 500 shouldn't be served from the cache later). Requests that aren't GET go to the network as if there were no service worker: don't answer them at all.
The tests give handleFetch a stand-in FetchEvent (fetchEvent()), an in-memory Cache Storage (useCaches()), and a stand-in fetch (useFetch()), each following the Service Workers and Fetch specs, so respondWith() only works while the event is being handled and a response's body can only be read once.
solution.js// The tea shop's service worker calls this for every request its pages make:
// self.addEventListener("fetch", handleFetch);
const CACHE = "tea-shop-v1";
function handleFetch(event) {
// Today every request goes to the network, even for files the shop has already stored.
event.respondWith(fetch(event.request));
}
- answers from the cache when the file is there, without asking the network
- on a miss, answers from the network and stores the file for next time
- the page and the cache each get the whole body: the response is cloned before it's stored
- the second request for a file is answered from the cache
- doesn't store a response that failed
- leaves requests that aren't GET to the browser
The answer
Write it yourself first. Then compare it with a reference solution and the checks it passes.
Checking your sign-in…