segregate cache by api key header

This commit is contained in:
Lee Salminen
2022-07-04 12:32:28 -06:00
parent d0ba5c6f30
commit d88ffeb237

View File

@ -1,12 +1,10 @@
// the cache version gets updated every time there is a new deployment // the cache version gets updated every time there is a new deployment
const CACHE_VERSION = 1; const CACHE_VERSION = 1;
const CURRENT_CACHE = `lnbits-${CACHE_VERSION}`; const CURRENT_CACHE = `lnbits-${CACHE_VERSION}-`;
// these are the routes we are going to cache for offline support const getApiKey = (request) => {
const cacheFiles = [ return request.headers.get('X-Api-Key') || "none"
'/core/static/js/wallet.js', }
'/core/static/js/extensions.js',
];
// on activation we clean up the previously registered service workers // on activation we clean up the previously registered service workers
self.addEventListener('activate', evt => self.addEventListener('activate', evt =>
@ -14,7 +12,8 @@ self.addEventListener('activate', evt =>
caches.keys().then(cacheNames => { caches.keys().then(cacheNames => {
return Promise.all( return Promise.all(
cacheNames.map(cacheName => { cacheNames.map(cacheName => {
if (cacheName !== CURRENT_CACHE) { const currentCacheVersion = cacheName.split('-').slice(-2)
if (currentCacheVersion !== CACHE_VERSION) {
return caches.delete(cacheName); return caches.delete(cacheName);
} }
}) })
@ -23,15 +22,6 @@ self.addEventListener('activate', evt =>
) )
); );
// on install we download the routes we want to cache for offline
self.addEventListener('install', evt =>
evt.waitUntil(
caches.open(CURRENT_CACHE).then(cache => {
return cache.addAll(cacheFiles);
})
)
);
// fetch the resource from the network // fetch the resource from the network
const fromNetwork = (request, timeout) => const fromNetwork = (request, timeout) =>
new Promise((fulfill, reject) => { new Promise((fulfill, reject) => {
@ -46,7 +36,7 @@ const fromNetwork = (request, timeout) =>
// fetch the resource from the browser cache // fetch the resource from the browser cache
const fromCache = request => const fromCache = request =>
caches caches
.open(CURRENT_CACHE) .open(CURRENT_CACHE + getApiKey(request))
.then(cache => .then(cache =>
cache cache
.match(request) .match(request)
@ -56,7 +46,7 @@ const fromCache = request =>
// cache the current page to make it available for offline // cache the current page to make it available for offline
const update = request => const update = request =>
caches caches
.open(CURRENT_CACHE) .open(CURRENT_CACHE + getApiKey(request))
.then(cache => .then(cache =>
fetch(request).then(response => cache.put(request, response)) fetch(request).then(response => cache.put(request, response))
); );