This commit is contained in:
2026-06-06 09:49:43 +05:30
parent cb81d476a8
commit 6e5ce9eb86
10 changed files with 496 additions and 15 deletions

80
public/sw.js Normal file
View File

@@ -0,0 +1,80 @@
const CACHE_NAME = 'brew-journal-v1';
// Static assets to cache immediately
const PRECACHE_ASSETS = [
'/',
'/index.html',
'/manifest.json',
'/favicon.svg',
'/icon-192.png',
'/icon-512.png'
];
// Install Event
self.addEventListener('install', (e) => {
e.waitUntil(
caches.open(CACHE_NAME).then((cache) => {
return cache.addAll(PRECACHE_ASSETS);
})
);
self.skipWaiting();
});
// Activate Event
self.addEventListener('activate', (e) => {
e.waitUntil(
caches.keys().then((keys) => {
return Promise.all(
keys.map((key) => {
if (key !== CACHE_NAME) {
return caches.delete(key);
}
})
);
})
);
self.clients.claim();
});
// Fetch Event
self.addEventListener('fetch', (e) => {
const url = new URL(e.request.url);
// Bypass API requests - always network-only for backend API calls
if (url.pathname.startsWith('/api/')) {
e.respondWith(fetch(e.request));
return;
}
// Stale-while-revalidate for static assets
e.respondWith(
caches.match(e.request).then((cachedResponse) => {
if (cachedResponse) {
// Fetch new version in background to update cache
fetch(e.request).then((networkResponse) => {
if (networkResponse.status === 200) {
caches.open(CACHE_NAME).then((cache) => {
cache.put(e.request, networkResponse);
});
}
}).catch(() => {/* Ignore network errors offline */});
return cachedResponse;
}
// Network fallback
return fetch(e.request).then((networkResponse) => {
if (!networkResponse || networkResponse.status !== 200 || networkResponse.type !== 'basic') {
return networkResponse;
}
const responseToCache = networkResponse.clone();
caches.open(CACHE_NAME).then((cache) => {
cache.put(e.request, responseToCache);
});
return networkResponse;
});
})
);
});