Use async/await in service worker, do not wait for cache open/put for successful requests
This commit is contained in:
parent
a6c0fa8926
commit
bb28ecaff7
@ -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"});
|
||||||
|
|
||||||
return Promise.reject("request-failed");
|
if (response.ok) {
|
||||||
})
|
event.waitUntil(putInCache(uri, response));
|
||||||
.catch(function() {
|
return response.clone();
|
||||||
return cache.match(uri).then(function(matching) {
|
}
|
||||||
return matching || Promise.reject("request-not-in-cache");
|
|
||||||
});
|
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 matching || Promise.reject("request-not-in-cache");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
self.addEventListener("message", function(event) {
|
self.addEventListener("message", function(event) {
|
||||||
|
Loading…
Reference in New Issue
Block a user