diff options
Diffstat (limited to 'src')
| -rw-r--r-- | src/worker.ts | 27 |
1 files changed, 24 insertions, 3 deletions
diff --git a/src/worker.ts b/src/worker.ts index e7133e4..0a9f1ec 100644 --- a/src/worker.ts +++ b/src/worker.ts @@ -8,6 +8,27 @@ const CACHE_VERSION = BUILD_CACHE_VERSION; const CACHE_NAME = CACHE_PREFIX + "-" + CACHE_VERSION; const MANIFEST_ASSETS = BUILD_MANIFEST_ASSETS; +function fetchWithTimeout(request: Request, timeoutMs = 2500): Promise<Response> { + return new Promise((resolve, reject) => { + // Create an abort controller to stop the native network request if the timer fires first + const controller = new AbortController(); + const timeoutId = setTimeout(() => { + controller.abort(); + reject(new Error("Network timeout: DNS resolution took too long.")); + }, timeoutMs); + + fetch(request, { signal: controller.signal }) + .then((response) => { + clearTimeout(timeoutId); + resolve(response); + }) + .catch((err) => { + clearTimeout(timeoutId); + reject(err); + }); + }); +} + // Install: precache all assets from manifest sw.addEventListener('install', (event) => { (event as any).waitUntil((async () => { @@ -86,7 +107,7 @@ sw.addEventListener('fetch', (event) => { if (url.pathname.match('backend.php')) { (event as any).respondWith((async () => { try { - const networkResp = await fetch((event as any).request); + const networkResp = await fetchWithTimeout((event as any).request); if (networkResp.ok) { const cache = await caches.open(CACHE_NAME); await cache.put(networkResp.url, networkResp.clone()); @@ -106,7 +127,7 @@ sw.addEventListener('fetch', (event) => { if (url.pathname == "/" || url.pathname.match("index.html|offline.html|read.html")) { (event as any).respondWith((async () => { try { - const networkResp = await fetch((event as any).request); + const networkResp = await fetchWithTimeout((event as any).request); if (networkResp.ok) { const cache = await caches.open(CACHE_NAME); await cache.put(networkResp.url, networkResp.clone()); @@ -116,7 +137,7 @@ sw.addEventListener('fetch', (event) => { catch (err) { // i.e. read.html?id=1234&b=1234 if (url.pathname.includes("read.html")) { - return caches.match("read.html"); + return caches.match("/read.html"); } else { return caches.match('/offline.html'); |
