purge phone calls and messages from cache when switching phone numbers or twilio account

This commit is contained in:
m5r
2022-06-11 16:13:00 +02:00
parent 1e9b7a8aa2
commit dbe209c7fc
7 changed files with 73 additions and 28 deletions

View File

@ -17,6 +17,10 @@ export function isDocumentGetRequest(request: Request) {
return request.method.toLowerCase() === "get" && request.mode === "navigate";
}
export function isMutationRequest(request: Request) {
return ["POST", "DELETE"].includes(request.method);
}
export function fetchAsset(event: FetchEvent): Promise<Response> {
// stale-while-revalidate
const url = new URL(event.request.url);
@ -172,5 +176,30 @@ export async function deleteCaches() {
const allCaches = await caches.keys();
const cachesToDelete = allCaches.filter((cacheName) => cacheName !== ASSET_CACHE);
await Promise.all(cachesToDelete.map((cacheName) => caches.delete(cacheName)));
console.debug("Caches deleted");
console.debug("Old caches deleted");
}
export async function purgeMutatedLoaders(event: FetchEvent) {
const url = new URL(event.request.url);
const rootPathname = "/" + url.pathname.split("/")[1];
const cache = await caches.open(DATA_CACHE);
const cachedLoaders = await cache.keys();
const loadersToDelete = cachedLoaders.filter((loader) => {
const cachedPathname = new URL(loader.url).pathname;
const shouldPurge = cachedPathname.startsWith(rootPathname);
if (url.pathname === "/settings/phone") {
// changes phone number or twilio account credentials
// so purge messages and phone calls from cache
return (
shouldPurge ||
["/messages", "/calls", "/keypad"].some((pathname) => cachedPathname.startsWith(pathname))
);
}
return shouldPurge;
});
await Promise.all(loadersToDelete.map((loader) => cache.delete(loader)));
console.debug("Purged loaders data starting with", rootPathname);
}

View File

@ -5,6 +5,8 @@ import {
isAssetRequest,
isDocumentGetRequest,
isLoaderRequest,
isMutationRequest,
purgeMutatedLoaders,
} from "./cache-utils";
declare const self: ServiceWorkerGlobalScope;
@ -22,5 +24,9 @@ export default async function handleFetch(event: FetchEvent) {
return fetchDocument(event);
}
if (isMutationRequest(event.request)) {
await purgeMutatedLoaders(event);
}
return fetch(event.request);
}

View File

@ -51,9 +51,5 @@ async function purgeStaticAssets(assetsToCache: string[]) {
const assetCache = await caches.open(ASSET_CACHE);
const cachedAssets = await assetCache.keys();
const cachesToDelete = cachedAssets.filter((asset) => !assetsToCache.includes(new URL(asset.url).pathname));
console.log(
"cachesToDelete",
cachesToDelete.map((c) => new URL(c.url).pathname),
);
await Promise.all(cachesToDelete.map((asset) => assetCache.delete(asset)));
}