Files
wareApp/client/public/sw.js

95 lines
2.7 KiB
JavaScript

// Service Worker for WarehouseTrack Pro PWA
const CACHE_NAME = 'warehousetrack-v1';
const urlsToCache = [
'/',
'/manifest.json',
'/src/index.css',
'/src/main.tsx',
'https://fonts.googleapis.com/css2?family=Roboto:ital,wght@0,300;0,400;0,500;0,700;1,300;1,400;1,500;1,700&display=swap'
];
// Install event
self.addEventListener('install', (event) => {
event.waitUntil(
caches.open(CACHE_NAME)
.then((cache) => cache.addAll(urlsToCache))
.then(() => self.skipWaiting())
);
});
// Activate event
self.addEventListener('activate', (event) => {
event.waitUntil(
caches.keys().then((cacheNames) => {
return Promise.all(
cacheNames.map((cacheName) => {
if (cacheName !== CACHE_NAME) {
return caches.delete(cacheName);
}
})
);
}).then(() => self.clients.claim())
);
});
// Fetch event - Network First Strategy for API calls, Cache First for static assets
self.addEventListener('fetch', (event) => {
const { request } = event;
// Handle API requests with network-first strategy
if (request.url.includes('/api/')) {
event.respondWith(
fetch(request)
.then((response) => {
// Don't cache POST/PUT/DELETE requests
if (request.method === 'GET' && response.status === 200) {
const responseClone = response.clone();
caches.open(CACHE_NAME)
.then((cache) => cache.put(request, responseClone));
}
return response;
})
.catch(() => {
// Fall back to cache if network fails
return caches.match(request);
})
);
return;
}
// Handle static assets with cache-first strategy
event.respondWith(
caches.match(request)
.then((response) => {
// Return cached version or fetch from network
return response || fetch(request)
.then((response) => {
// Don't cache non-successful responses
if (!response || response.status !== 200 || response.type !== 'basic') {
return response;
}
const responseToCache = response.clone();
caches.open(CACHE_NAME)
.then((cache) => cache.put(request, responseToCache));
return response;
});
})
);
});
// Handle background sync for offline actions
self.addEventListener('sync', (event) => {
if (event.tag === 'stock-update') {
event.waitUntil(
// Handle offline stock updates when back online
handleOfflineStockUpdates()
);
}
});
// Placeholder function for handling offline updates
function handleOfflineStockUpdates() {
return Promise.resolve();
}