Use async/await in service worker, do not wait for cache open/put for successful requests

This commit is contained in:
Pavel Djundik 2019-03-07 21:14:50 +02:00
parent a6c0fa8926
commit bb28ecaff7

View File

@ -2,6 +2,7 @@
/* global clients */ /* global clients */
"use strict"; "use strict";
const cacheName = "thelounge";
const excludedPathsFromCache = /^(?:socket\.io|storage|uploads|cdn-cgi)\//; const excludedPathsFromCache = /^(?:socket\.io|storage|uploads|cdn-cgi)\//;
self.addEventListener("install", function() { self.addEventListener("install", function() {
@ -36,31 +37,33 @@ self.addEventListener("fetch", function(event) {
uri.hash = ""; uri.hash = "";
uri.search = ""; uri.search = "";
event.respondWith(networkOrCache(uri)); event.respondWith(networkOrCache(event, uri));
}); });
function networkOrCache(uri) { async function putInCache(uri, response) {
return caches.open("thelounge").then(function(cache) { const cache = await caches.open(cacheName);
// Despite the "no-cache" name, it is a conditional request if proper headers are set await cache.put(uri, response);
return fetch(uri, {cache: "no-cache"})
.then(function(response) {
if (response.ok) {
return cache.put(uri, response.clone()).then(function() {
return response;
});
} }
// eslint-disable-next-line no-console async function networkOrCache(event, uri) {
console.error(`Request for ${uri.href} failed with HTTP ${response.status}`); try {
const response = await fetch(uri, {cache: "no-cache"});
if (response.ok) {
event.waitUntil(putInCache(uri, response));
return response.clone();
}
throw new Error(`Request failed with HTTP ${response.status}`);
} catch (e) {
// eslint-disable-next-line no-console
console.error(e.message, uri.href);
const cache = await caches.open(cacheName);
const matching = await cache.match(uri);
return Promise.reject("request-failed");
})
.catch(function() {
return cache.match(uri).then(function(matching) {
return matching || Promise.reject("request-not-in-cache"); return matching || Promise.reject("request-not-in-cache");
}); }
});
});
} }
self.addEventListener("message", function(event) { self.addEventListener("message", function(event) {