add comments and docs to sw.js,

add service worker ADR
This commit is contained in:
Arthur Lu 2022-12-01 08:37:49 +00:00
parent 1ed46b8ade
commit 7cb90e23c0
2 changed files with 37 additions and 4 deletions

View File

@ -28,20 +28,34 @@ const ASSETS = [
"assets/scripts/ReviewDetails.js", "assets/scripts/ReviewDetails.js",
]; ];
/**
* Adds the install listener where the app assets are added to the cache
*/
self.addEventListener("install", async () => { self.addEventListener("install", async () => {
// open the cace
const cache = await caches.open(CACHE_NAME); const cache = await caches.open(CACHE_NAME);
// add all elements in ASSETS to the cache, these are all the files requried for the app to run
await cache.addAll(ASSETS); await cache.addAll(ASSETS);
}); });
/**
* Adds an event listener on fetch events to serve cached resources while offline
* Uses a network first structure to prioritize fetching from network in case of app updates.
* If there are important updates, we want the user to get those if possible.
*/
self.addEventListener("fetch", (event) => { self.addEventListener("fetch", (event) => {
console.log(`fetching: ${event.request.url}`); // add a response to the fetch event
event.respondWith(caches.open(CACHE_NAME).then((cache) => { event.respondWith(caches.open(CACHE_NAME).then((cache) => {
// try to return a network fetch response
return fetch(event.request).then((fetchedResponse) => { return fetch(event.request).then((fetchedResponse) => {
// if there is a response, add it to the cache
cache.put(event.request, fetchedResponse.clone()); cache.put(event.request, fetchedResponse.clone());
console.log(typeof(fetchedResponse)); // return the network response
return fetchedResponse; return fetchedResponse;
}).catch(() => { }).catch(() => {
console.log(cache.match(event.request, {ignoreVary: true})); // If there is not a network response, return the cached response
// The ignoreVary option is used here to fix an issue where the service worker
// would not serve certain requests unless the page was refreshed at least once
return cache.match(event.request, {ignoreVary: true}); return cache.match(event.request, {ignoreVary: true});
}); });
})); }));

View File

@ -0,0 +1,19 @@
# Use a network first cache second for service worker architecture
- Status: in consideration
- Deciders: Arthur Lu
- Date: 12 / 02 / 22
## Decision Drivers
- Need to balance the need for user ease of use and local first priority
- Users should expect to update their app easily when they have network, but may not be expected to know how to perform a hard refresh
- Local first priority means we should avoid unnecessary network activity when possible
## Considered Options
- Network first cache second
- Cache first network second
## Decision Outcome
Chosen Option: TBD