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