feat: implement offline synchronization with mutation queue and background sync
- Created useOfflineSync hook for connectivity detection and sync management - Implemented localStorage-based mutation queue for offline operations - Added background sync support in service worker - Created OfflineIndicator component to show connection status - Added offline-aware action wrappers for seamless offline/online transitions - Implemented conflict handling with retry logic (up to 3 retries) - Auto-sync when connection is restored - Validates Requirements 4.5
This commit is contained in:
39
public/sw.js
39
public/sw.js
@@ -162,3 +162,42 @@ async function networkFirst(request) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// Background Sync - sync pending mutations when connection is restored
|
||||
self.addEventListener('sync', (event) => {
|
||||
if (event.tag === 'sync-mutations') {
|
||||
event.waitUntil(syncMutations());
|
||||
}
|
||||
});
|
||||
|
||||
// Sync mutations from the queue
|
||||
async function syncMutations() {
|
||||
try {
|
||||
// Notify all clients to trigger sync
|
||||
const clients = await self.clients.matchAll();
|
||||
clients.forEach((client) => {
|
||||
client.postMessage({
|
||||
type: 'SYNC_MUTATIONS',
|
||||
});
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Background sync failed:', error);
|
||||
throw error; // Re-throw to retry later
|
||||
}
|
||||
}
|
||||
|
||||
// Listen for messages from clients
|
||||
self.addEventListener('message', (event) => {
|
||||
if (event.data && event.data.type === 'SKIP_WAITING') {
|
||||
self.skipWaiting();
|
||||
}
|
||||
|
||||
if (event.data && event.data.type === 'REGISTER_SYNC') {
|
||||
// Register background sync
|
||||
if (self.registration.sync) {
|
||||
self.registration.sync.register('sync-mutations').catch((error) => {
|
||||
console.error('Failed to register background sync:', error);
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user