forked from antun-nakic/PWAfrontend2022
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsw.js
62 lines (56 loc) · 1.91 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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
const cacheName = "nasPrviPWA-v1";
const OFFLINE_URL = "/PWAfrontend2022/offline.html";
self.addEventListener("install", (e) => {
console.log("[Service Worker] Install");
e.waitUntil(
(async () => {
const cache = await caches.open(cacheName);
console.log("[Service Worker] Caching all: app shell and content");
await cache.add(new Request(OFFLINE_URL, { cache: "reload" }));
})()
);
});
self.addEventListener("fetch", (e) => {
e.respondWith(
(async () => {
try {
const cache = await caches.open(cacheName);
//ako se traži podatak o vremenu, probaj dohvatiti s interneta
if (e.request.url.includes("https://api.weatherapi.com/v1/")) {
//probaj ici na internet dohvatiti to
const response = await fetch(e.request);
console.log(
`[Service Worker] Caching new resource: ${e.request.url}`
);
let vraceno = response.clone();
const newHeaders = new Headers(vraceno.headers);
newHeaders.set("cache", "true");
const newResponse = new Response(vraceno.body, {
headers: newHeaders,
});
cache.put(e.request, newResponse);
return response;
} else {
//serviraj chacheani podatak ako postoji
const r = await caches.match(e.request);
if (r) {
return r;
}
//probaj ici na internet dohvatiti to
const response = await fetch(e.request);
cache.put(e.request, response.clone());
return response;
}
} catch (error) {
console.log("Fetch failed; returning offline page instead.", error);
console.log(e.request);
const r = await caches.match(e.request);
console.log(
`[Service Worker] Fetching resource from chache: ${e.request.url}`
);
console.log(r);
if (r) return r;
}
})()
);
});