85 lines
2.6 KiB
JavaScript
85 lines
2.6 KiB
JavaScript
/**
|
|
* MobileApp Service Worker
|
|
* Provides basic caching for the PWA shell and assets.
|
|
*/
|
|
|
|
const CACHE_NAME = 'xinon-mobile-v1';
|
|
const ASSETS_TO_CACHE = [
|
|
'/MobileApp',
|
|
'/mobile/app.js',
|
|
'/mobile/shared/auth.js',
|
|
'/mobile/shared/base.css',
|
|
'/mobile/components/LoginScreen.js',
|
|
'/mobile/components/MainMenu.js',
|
|
'/mobile/modules/lager/LagerModule.js',
|
|
'/mobile/modules/lager/inventur/StocktakeList.js',
|
|
'/mobile/modules/lager/inventur/Scanner.js',
|
|
'/assets/images/xinon-full-transparent.png',
|
|
'/assets/images/xinon-full-transparent-white.png',
|
|
'/assets/images/xinon-sm.png'
|
|
];
|
|
|
|
// Install: cache assets
|
|
self.addEventListener('install', (event) => {
|
|
event.waitUntil(
|
|
caches.open(CACHE_NAME)
|
|
.then(cache => cache.addAll(ASSETS_TO_CACHE))
|
|
.then(() => self.skipWaiting())
|
|
);
|
|
});
|
|
|
|
// Activate: clean old caches
|
|
self.addEventListener('activate', (event) => {
|
|
event.waitUntil(
|
|
caches.keys().then(cacheNames => {
|
|
return Promise.all(
|
|
cacheNames
|
|
.filter(name => name !== CACHE_NAME)
|
|
.map(name => caches.delete(name))
|
|
);
|
|
}).then(() => self.clients.claim())
|
|
);
|
|
});
|
|
|
|
// Fetch: network-first for API, cache-first for assets
|
|
self.addEventListener('fetch', (event) => {
|
|
// Only handle GET requests
|
|
if (event.request.method !== 'GET') return;
|
|
|
|
const url = new URL(event.request.url);
|
|
|
|
// API calls: network only
|
|
if (url.pathname.startsWith('/MobileApp/') &&
|
|
url.pathname !== '/MobileApp' &&
|
|
url.pathname !== '/MobileApp/') {
|
|
return;
|
|
}
|
|
|
|
// Everything else: cache-first, falling back to network
|
|
event.respondWith(
|
|
caches.match(event.request).then(cached => {
|
|
if (cached) {
|
|
// Return cached, but update in background
|
|
fetch(event.request).then(response => {
|
|
if (response.ok) {
|
|
caches.open(CACHE_NAME).then(cache => {
|
|
cache.put(event.request, response);
|
|
});
|
|
}
|
|
}).catch(() => {});
|
|
return cached;
|
|
}
|
|
|
|
return fetch(event.request).then(response => {
|
|
if (response.ok && url.origin === location.origin) {
|
|
const clone = response.clone();
|
|
caches.open(CACHE_NAME).then(cache => {
|
|
cache.put(event.request, clone);
|
|
});
|
|
}
|
|
return response;
|
|
});
|
|
})
|
|
);
|
|
});
|