fix: Service Worker always returns valid Response
- Fixed fetch handler that could return undefined instead of Response - Changed from stale-while-revalidate to network-first with cache fallback - Always return proper 503 Response when offline and no cache available - Bump cache version to v21 to force SW update
This commit is contained in:
23
public/sw.js
23
public/sw.js
@@ -1,4 +1,4 @@
|
|||||||
const CACHE_NAME = 'whisky-vault-v20-offline';
|
const CACHE_NAME = 'whisky-vault-v21-offline';
|
||||||
|
|
||||||
// CONFIG: Assets - Only essential files, no heavy OCR (~2MB instead of ~50MB)
|
// CONFIG: Assets - Only essential files, no heavy OCR (~2MB instead of ~50MB)
|
||||||
const STATIC_ASSETS = [
|
const STATIC_ASSETS = [
|
||||||
@@ -189,22 +189,33 @@ self.addEventListener('fetch', (event) => {
|
|||||||
if (isNavigation || isAsset) {
|
if (isNavigation || isAsset) {
|
||||||
event.respondWith(
|
event.respondWith(
|
||||||
caches.match(event.request).then(async (cachedResponse) => {
|
caches.match(event.request).then(async (cachedResponse) => {
|
||||||
const fetchPromise = fetchWithTimeout(event.request, 10000)
|
// Try network first
|
||||||
.then(async (networkResponse) => {
|
try {
|
||||||
|
const networkResponse = await fetchWithTimeout(event.request, 10000);
|
||||||
if (networkResponse && networkResponse.status === 200) {
|
if (networkResponse && networkResponse.status === 200) {
|
||||||
const cache = await caches.open(CACHE_NAME);
|
const cache = await caches.open(CACHE_NAME);
|
||||||
cache.put(event.request, networkResponse.clone());
|
cache.put(event.request, networkResponse.clone());
|
||||||
}
|
}
|
||||||
return networkResponse;
|
return networkResponse;
|
||||||
}).catch(() => { });
|
} catch (networkError) {
|
||||||
|
// Network failed, fall back to cache
|
||||||
|
if (cachedResponse) {
|
||||||
|
return cachedResponse;
|
||||||
|
}
|
||||||
|
|
||||||
|
// For navigation, try to serve the app shell
|
||||||
if (isNavigation) {
|
if (isNavigation) {
|
||||||
if (cachedResponse) return cachedResponse;
|
|
||||||
const shell = await caches.match('/');
|
const shell = await caches.match('/');
|
||||||
if (shell) return shell;
|
if (shell) return shell;
|
||||||
}
|
}
|
||||||
|
|
||||||
return cachedResponse || fetchPromise || fetch(event.request);
|
// Last resort: return a proper error response
|
||||||
|
return new Response('Offline - Resource not available', {
|
||||||
|
status: 503,
|
||||||
|
statusText: 'Service Unavailable',
|
||||||
|
headers: { 'Content-Type': 'text/plain' }
|
||||||
|
});
|
||||||
|
}
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user