Skip to content

Commit

Permalink
feat: open caches and add fallback on sw interception (#139)
Browse files Browse the repository at this point in the history
  • Loading branch information
userquin committed Apr 22, 2023
1 parent 3371cc4 commit 74724b7
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 17 deletions.
1 change: 1 addition & 0 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ const router = createRouter({
if (!isElectron && PWA) {
// disable local storage cache when there is PWA:
// we need to keep local storage when running dev server without PWA
// to avoid call iconify server api
disableCache('all')
router.isReady().then(async () => {
const { registerSW } = await import('virtual:pwa-register')
Expand Down
50 changes: 33 additions & 17 deletions src/sw.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { cleanupOutdatedCaches, createHandlerBoundToURL, precacheAndRoute } from 'workbox-precaching'
import { clientsClaim } from 'workbox-core'
import { cacheNames, clientsClaim } from 'workbox-core'
import { NavigationRoute, registerRoute } from 'workbox-routing'
import { getIcons } from '@iconify/utils'

Expand All @@ -19,24 +19,40 @@ registerRoute(new NavigationRoute(
self.skipWaiting()
clientsClaim()

async function getCollection(request: Request, name: string, icons: string[]) {
try {
const cache = await caches.open(cacheNames.precache)
const url = `/collections/${name}-raw.json`
let cachedResponse = await cache.match(url)
if (!cachedResponse) {
cachedResponse = await fetch(url)
await cache.put(url, cachedResponse.clone())
}
const collection = await cachedResponse.json()
return new Response(JSON.stringify(getIcons(
collection,
icons,
)), {
headers: {
'Content-Type': 'application/json; charset=utf-8',
},
})
}
catch {
return await fetch(request)
}
}

const fetchRegex = /^https:\/\/(api\.iconify\.design|api\.simplesvg\.com|api\.unisvg\.com)\/(.*)\.json\?icons=(.*)$/

self.addEventListener('fetch', (e) => {
const url = e.request.url
const match = url.match(/^https:\/\/(api\.iconify\.design|api\.simplesvg\.com|api\.unisvg\.com)\/(.*)\.json\?icons=(.*)?/)
const match = url.match(fetchRegex)
if (match) {
e.respondWith(
fetch(`/collections/${match[2]}-raw.json`)
.then((response) => {
return response.json()
}).then((collection) => {
return new Response(JSON.stringify(getIcons(
collection,
match[3].replaceAll('%2C', ',').split(','),
)), {
headers: {
'Content-Type': 'application/json',
},
})
}),
)
e.respondWith(getCollection(
e.request,
match[2],
match[3].replaceAll('%2C', ',').split(','),
))
}
})

0 comments on commit 74724b7

Please sign in to comment.