Skip to content
Permalink
Browse files

update caching strategy to work with missing cache items

  • Loading branch information...
slatron committed Sep 4, 2019
1 parent 6292753 commit 90eb108d1a91dd8ecf2c000ab3acae015c4a42e4
Showing with 26 additions and 20 deletions.
  1. +21 −19 public/cache.js
  2. +5 −1 src/main.js
@@ -6,25 +6,27 @@ const CACHE_NAME = 'Slatronica'

self.onfetch = function(event) {
event.respondWith(
caches.match(event.request)
.then(cachedFiles => {
return cachedFiles || fetch(event.request)
.then(response => {
// cache scryfall API responses and jpg images
const requestUrl = event.request.url
if (requestUrl.startsWith(URL_TO_CACHE) || requestUrl.startsWith(IMG_TO_CACHE)) {
caches.open(CACHE_NAME)
.then(cache => {
cache.put(event.request, response.clone())
return response;
})
.catch(err => console.log('OOPS! cache.js err on cache.open :', err))
}
return response
})
.catch(err => console.log('OOPS! cache.js err on fetch(event.request) :', err))
})
.catch(err => console.log('OOPS! cache.js err on caches.match(event.request) :', err))
(async function() {
var cache = await caches.open(CACHE_NAME);
var cachedFiles = await cache.match(event.request)
if(cachedFiles) {
return cachedFiles
} else {
try {
var response = await fetch(event.request);
const requestUrl = event.request.url
if (requestUrl.startsWith(URL_TO_CACHE) || requestUrl.startsWith(IMG_TO_CACHE)) {
await cache.put(event.request, response.clone())
return response
} else {
return fetch(event.request)
}
} catch(e) {
console.log('ERROR from cache.js await fetch block: ', e)
return fetch(event.request)
}
}
}())
)
}

@@ -10,7 +10,11 @@ window.addEventListener('load', () => {
return
}

navigator.serviceWorker.register('/cache.js').then(
const baseUrl = window.location.host === 'localhost:8080'
? '/'
: '/slatronica-mtg/'

navigator.serviceWorker.register(`${baseUrl}cache.js`).then(
() => console.log('Successfully registered cache worker'),
err => console.warn('Service worker registration failed')
)

0 comments on commit 90eb108

Please sign in to comment.
You can’t perform that action at this time.