forked from udacity/mws-restaurant-stage-1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsw.js
37 lines (34 loc) · 1016 Bytes
/
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
const expectedCacheName = 'mws-restaurant-cache-v5';
self.addEventListener('activate', event => event.waitUntil(
caches.keys().then(cacheNames => Promise.all(
cacheNames.map((cacheName) => {
if (cacheName !== expectedCacheName) {
console.log('Deleting out of date cache:', cacheName);
return caches.delete(cacheName);
}
}),
)),
));
self.addEventListener('fetch', (event) => {
const url = new URL(event.request.url);
if (url.port === '1337') {
console.log('not caching api', event.request.url);
return fetch(event.request);
}
event.respondWith(
caches
.open(expectedCacheName)
.then(cache => cache
.match(event.request)
.then((cachedResponse) => {
if (cachedResponse) {
return cachedResponse;
}
return fetch(event.request)
.then((response) => {
cache.put(event.request, response.clone());
return response;
});
})),
);
});