1class OfflineSyncManager {
2 constructor(db, apiEndpoint) {
3 this.db = db;
4 this.apiEndpoint = apiEndpoint;
5 this.isSyncing = false;
6
7 this.initNetworkListeners();
8 }
9
10 initNetworkListeners() {
11 // Listen for network restoration
12 window.addEventListener('online', () => {
13 console.log('[Network] Internet connection restored! Triggering sync...');
14 this.syncOutbox();
15 });
16
17 window.addEventListener('offline', () => {
18 console.warn('[Network] Device went offline. Mutations queued locally.');
19 });
20 }
21
22 // Enqueue an action to be executed remotely
23 async queueMutation(mutation) {
24 const record = {
25 id: 'mut_' + crypto.randomUUID(),
26 type: mutation.type,
27 payload: mutation.payload,
28 createdAt: Date.now(),
29 retryCount: 0
30 };
31
32 // Save to IndexedDB 'outbox' store
33 await this.writeToStore('outbox', record);
34
35 // If currently online, trigger sync immediately
36 if (navigator.onLine) {
37 this.syncOutbox();
38 }
39 }
40
41 async syncOutbox() {
42 if (this.isSyncing || !navigator.onLine) return;
43 this.isSyncing = true;
44
45 try {
46 const pendingMutations = await this.getAllFromStore('outbox');
47 console.log(`[Sync] Processing ${pendingMutations.length} pending mutations...`);
48
49 for (const mutation of pendingMutations) {
50 try {
51 // Dispatch to remote server
52 const response = await fetch(this.apiEndpoint, {
53 method: 'POST',
54 headers: { 'Content-Type': 'application/json' },
55 body: JSON.stringify(mutation)
56 });
57
58 if (response.ok) {
59 // Success! Remove from outbox
60 await this.deleteFromStore('outbox', mutation.id);
61 console.log(`[Sync] Mutation ${mutation.id} synced successfully.`);
62 } else if (response.status >= 400 && response.status < 500) {
63 // Client error (unrecoverable): discard to prevent outbox blocking
64 await this.deleteFromStore('outbox', mutation.id);
65 }
66 } catch (netErr) {
67 console.warn('[Sync] Network error during batch; halting sync until online.');
68 break; // Stop loop; will retry on next 'online' event
69 }
70 }
71 } finally {
72 this.isSyncing = false;
73 }
74 }
75
76 // IndexedDB Promise Helpers
77 writeToStore(storeName, data) {
78 return new Promise((resolve, reject) => {
79 const tx = this.db.transaction([storeName], 'readwrite');
80 tx.objectStore(storeName).put(data);
81 tx.oncomplete = () => resolve();
82 tx.onerror = () => reject(tx.error);
83 });
84 }
85
86 getAllFromStore(storeName) {
87 return new Promise((resolve, reject) => {
88 const tx = this.db.transaction([storeName], 'readonly');
89 const req = tx.objectStore(storeName).getAll();
90 req.onsuccess = () => resolve(req.result);
91 req.onerror = () => reject(req.error);
92 });
93 }
94
95 deleteFromStore(storeName, key) {
96 return new Promise((resolve, reject) => {
97 const tx = this.db.transaction([storeName], 'readwrite');
98 tx.objectStore(storeName).delete(key);
99 tx.oncomplete = () => resolve();
100 tx.onerror = () => reject(tx.error);
101 });
102 }
103}