Created
September 30, 2020 03:41
-
-
Save oahehc/253282f0984ade0437708de63f7569ec to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| self.addEventListener("fetch", (event) => { | |
| // hijacking path and return a mock HTML content | |
| if (event.request.url.includes("/faq")) { | |
| event.respondWith( | |
| new Response("<div>Mock FAQ Page</div>", { | |
| headers: { "Content-Type": "text/html" }, | |
| }) | |
| ); | |
| } | |
| // hijacking API request and return mock response in JSON format | |
| if (event.request.url.includes("/api/users")) { | |
| const data = [ | |
| { | |
| id: "0001", | |
| name: "andrew", | |
| }, | |
| ]; | |
| const blob = new Blob( | |
| [JSON.stringify(data, null, 2)], | |
| { type: "application/json" } | |
| ); | |
| const init = { status: 200, statusText: "default mock response" }; | |
| const defaultResponse = new Response(blob, init); | |
| event.respondWith(defaultResponse); | |
| } | |
| // Stale-while-revalidate: | |
| // return the cached version if it exists. At the same time, | |
| // send a request to get the latest version and update the cache | |
| const requestUrl = new URL(event.request.url); | |
| if (requestUrl.pathname.startsWith("/avatars/")) { | |
| const response = caches.open(CACHE_NAME).then((cache) => { | |
| return cache.match(event.request).then((response) => { | |
| const networkFetch = fetch(event.request) | |
| .then((networkResponse) => { | |
| cache.put(event.request, networkResponse.clone()); | |
| return networkResponse; | |
| }); | |
| return response || networkFetch; | |
| }); | |
| }); | |
| event.respondWith(response); | |
| return; | |
| } | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment