Service worker cleanup

pull/454/head
Zef Hemel 2023-07-04 16:54:57 +02:00
parent f39ab26cea
commit 98bebf3cb8
1 changed files with 62 additions and 65 deletions

View File

@ -74,12 +74,12 @@ self.addEventListener("fetch", (event: any) => {
const cacheKey = precacheFiles[url.pathname] || event.request.url;
event.respondWith(
(async () => {
// Try the static (client) file cache first
caches.match(cacheKey)
.then((response) => {
const cachedResponse = await caches.match(cacheKey);
// Return the cached response if found
if (response) {
return response;
if (cachedResponse) {
return cachedResponse;
}
const requestUrl = new URL(event.request.url);
@ -88,19 +88,25 @@ self.addEventListener("fetch", (event: any) => {
// console.log("In service worker, pathname is", pathname);
// Are we fetching a URL from the same origin as the app? If not, we don't handle it here
const fetchingLocal = location.host === requestUrl.host;
if (!fetchingLocal) {
return fetch(event.request);
}
// If this is a /.fs request, this can either be a plug worker load or an attachment load
if (fetchingLocal && pathname.startsWith("/.fs")) {
if (fileContentTable && !event.request.headers.has("x-sync-mode")) {
if (pathname.startsWith("/.fs")) {
if (!fileContentTable || event.request.headers.has("x-sync-mode")) {
// Not initialzed yet, or explicitly in sync mode (so direct server communication requested)
return fetch(event.request);
}
// console.log(
// "Attempting to serve file from locally synced space:",
// pathname,
// );
// Don't fetch from DB when in sync mode (because then updates won't sync)
const path = decodeURIComponent(
requestUrl.pathname.slice("/.fs/".length),
);
return fileContentTable.get(path).then(
async (data) => {
const data = await fileContentTable.get(path);
if (data) {
// console.log("Serving from space", path);
if (!data.meta) {
@ -127,22 +133,13 @@ self.addEventListener("fetch", (event: any) => {
status: 404,
});
}
},
);
} else {
// Just fetch the file directly
} else if (pathname === "/.auth") {
return fetch(event.request);
}
} else if (fetchingLocal && pathname !== "/.auth") {
} else {
// Must be a page URL, let's serve index.html which will handle it
return caches.match(precacheFiles["/"]).then((response) => {
// This shouldnt't happen, index.html not in the cache for some reason
return response || fetch(event.request);
});
} else {
return fetch(event.request);
return (await caches.match(precacheFiles["/"])) || fetch(event.request);
}
}),
})(),
);
});