Skip to content

Commit

Permalink
feat: allow bypassing caches (#55)
Browse files Browse the repository at this point in the history
  • Loading branch information
razonyang committed Nov 24, 2023
1 parent 6919bdf commit bf8a4b9
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 0 deletions.
28 changes: 28 additions & 0 deletions assets/mods/pwa/service-worker/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ const fallbacksCache = cachePrefix + 'fallbacks'
// Filter the invalid URLs, such as temporary URLs generated by Hugo PostProgress.
const precaches = params.precaches.filter((url) => url.indexOf('__h_pp_l1') !== 0)
debug('precaches', precaches)
debug('bypass', params.bypass)

// Register page route with NetworkFirst strategy.
// There will be a problem with CacheFirst or StaleWhileRevalidate strategy
Expand All @@ -39,6 +40,33 @@ registerRoute(

// Register assets routes.
const assets = ['font', 'image', 'script', 'style']

const isBypass = (url) => {
if (params.bypass && params.bypass.includes(url.href)) {
return true
}

return false
}

if (params.bypass) {
registerRoute(
({ request, sameOrigin, url }) => {
if (!isBypass(url)) {
return false
}

// validate origins
if (sameOrigin) {
return true
}

return false
},
new NetworkOnly(),
);
}

for (let i in assets) {
const kind = assets[i]
const cache = params.caches[kind]
Expand Down
5 changes: 5 additions & 0 deletions layouts/partials/pwa/assets/sw.html
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
{{- $baseURL := partialCached "pwa/functions/baseurl" . }}
{{/* JS compile options. */}}
{{- $precaches := slice }}
{{- $bypass := slice }}
{{- $langs := slice }}
{{- $host := .Site.BaseURL }}
{{/* Get precaches pages. */}}
Expand All @@ -25,6 +26,9 @@
{{- with .Store.Get "pwa-precache" }}
{{- $precaches = $precaches | append (uniq .) }}
{{- end }}
{{- with .Store.Get "pwa-bypass" }}
{{- $bypass = $bypass | append (uniq .) }}
{{- end }}
{{- $pwaParams := .Site.Params.pwa }}
{{/* Get precaches from configuration. */}}
{{- range $pwaParams.precaches }}
Expand All @@ -48,6 +52,7 @@
"baseURL" $baseURL
"langs" $langs
"precaches" $precaches
"bypass" $bypass
"debug" $pwaParams.debug
"caches" $pwaParams.caches
"offline_image" $offlineImg
Expand Down
3 changes: 3 additions & 0 deletions layouts/partials/pwa/functions/bypass.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{{- if and .Page .URL }}
{{- .Page.Store.Add "pwa-bypass" (slice .URL) }}
{{- end }}

0 comments on commit bf8a4b9

Please sign in to comment.