refactor(pwa): ♻️ make generic getCache

This commit is contained in:
Julien Oculi 2024-07-19 14:57:54 +02:00
parent b6657b279d
commit 574c60c130

View file

@ -160,14 +160,9 @@ async function fetchHandler(event: FetchEvent) {
FetchStrategy.fastestAndCacheRefresh(cache, event)
}
// Network only
return FetchStrategy.networkOnly(event)
}
async function getDynCache(): Promise<Cache> {
const lifeTime = 1 * 24 * 3_600 * 1000 //1 day
async function getCache(name: string, lifeTime = 1 * 24 * 3_600 * 1000): Promise<Cache> {
const now = Date.now()
const version = await swStorage.getItem<number>('$sw.dyn-cache.version')
const version = await swStorage.getItem<number>(name)
// Get "cache" from ram
if (memory.has(version)) {
@ -176,15 +171,15 @@ async function getDynCache(): Promise<Cache> {
// Create cache
if (version === null) {
await swStorage.setItem<number>('$sw.dyn-cache.version', now + lifeTime)
return getDynCache()
await swStorage.setItem<number>(name, now + lifeTime)
return getCache(name, lifeTime)
}
// Clean outdated cache
if (version < Date.now()) {
await swStorage.setItem<number>('$sw.dyn-cache.version', now + lifeTime)
await swStorage.setItem<number>(name, now + lifeTime)
await caches.delete(version.toString())
return getDynCache()
return getCache(name, lifeTime)
}
// Get "cache" from fs