feat(pwa): update sw cache if version change between any request

This commit is contained in:
Julien Oculi 2024-07-17 13:18:19 +02:00
parent 654bc40358
commit ae1b87c253

View file

@ -86,6 +86,8 @@ async function fetchHandler(event: FetchEvent) {
const method = event.request.method const method = event.request.method
const preCachedUrls = await getPreCachedUrls() const preCachedUrls = await getPreCachedUrls()
const cache = await getCache() const cache = await getCache()
// Cache will be updated on each request if version change
updateCache()
// Cache first for "pre-cached-urls" // Cache first for "pre-cached-urls"
if (preCachedUrls.includes(url.pathname) && method === 'GET') { if (preCachedUrls.includes(url.pathname) && method === 'GET') {
@ -135,6 +137,24 @@ async function fetchHandler(event: FetchEvent) {
return fetch(event.request) return fetch(event.request)
} }
async function updateCache() {
const serverVersion = await getServerCacheVersion()
const clientVersion = await swStorage.getItem<string>('$sw.cache.version')
if (serverVersion === undefined) return
if (clientVersion === serverVersion) return
openCache()
}
async function getServerCacheVersion() {
const response = await fetch('/api/serviceworker/precache').then(
(response) => response.json() as Promise<ApiPayload<PrecacheResponse>>,
)
if (response.kind === 'success') {
return response.data.version
}
}
async function openCache() { async function openCache() {
const response = await fetch('/api/serviceworker/precache').then( const response = await fetch('/api/serviceworker/precache').then(
(response) => response.json() as Promise<ApiPayload<PrecacheResponse>>, (response) => response.json() as Promise<ApiPayload<PrecacheResponse>>,