forked from lifeconsciousness/rent-calculator-nodejs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsw.js
45 lines (40 loc) · 1.31 KB
/
sw.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
self.addEventListener('install', (event) => {
self.skipWaiting();
});
self.addEventListener('activate', (event) => {
clients.claim();
});
// Sync event listener
self.addEventListener('sync', (event) => {
if (event.tag === 'syncSearchRequest') {
event.waitUntil(processSyncQueue());
}
});
// Function to process requests stored in local storage
async function processSyncQueue() {
const queue = getQueuedRequests();
for (const request of queue) {
try {
await fetch(request.url, {
method: request.method,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(request.body),
});
removeRequestFromQueue(request.id); // Remove the successfully processed request
} catch (error) {
console.error('Background sync failed:', error);
break; // Stop further processing if there's an error
}
}
}
// Retrieve queued requests from local storage
function getQueuedRequests() {
const queue = localStorage.getItem('requestQueue');
return queue ? JSON.parse(queue) : [];
}
// Remove a processed request from the local storage queue
function removeRequestFromQueue(id) {
const queue = getQueuedRequests();
const updatedQueue = queue.filter((request) => request.id !== id);
localStorage.setItem('requestQueue', JSON.stringify(updatedQueue));
}