aboutsummaryrefslogtreecommitdiff
path: root/public
diff options
context:
space:
mode:
authorAriel Costas Guerrero <94913521+arielcostas@users.noreply.github.com>2025-03-03 18:54:35 +0100
committerAriel Costas Guerrero <94913521+arielcostas@users.noreply.github.com>2025-03-03 18:54:35 +0100
commit3aa6eee0f54dec3e4f92be2ad335a04145ac4db8 (patch)
tree9ccffabd2972249322ebaa6d1de26289d7a41a4c /public
parentd3726e50167ed07c483c542cf6739f103dda0dd5 (diff)
Improve the UI
Diffstat (limited to 'public')
-rw-r--r--public/sw.js51
1 files changed, 51 insertions, 0 deletions
diff --git a/public/sw.js b/public/sw.js
new file mode 100644
index 0000000..1aa9747
--- /dev/null
+++ b/public/sw.js
@@ -0,0 +1,51 @@
+const API_CACHE_NAME = 'api-cache-v1'
+const API_URL_PATTERN = /\/api\/(GetStopList)/;
+const API_MAX_AGE = 72 * 60 * 60 * 1000; // 72 hours
+
+self.addEventListener('install', (event) => {
+ event.waitUntil(self.skipWaiting());
+});
+
+self.addEventListener('activate', (event) => {
+ event.waitUntil(self.clients.claim());
+});
+
+self.addEventListener('fetch', async (event) => {
+ const url = new URL(event.request.url);
+
+ if (event.request.method !== "GET" || !API_URL_PATTERN.test(url.pathname)) {
+ return;
+ }
+
+ event.respondWith(apiCacheFirst(event.request));
+});
+
+async function apiCacheFirst(request) {
+ const cache = await caches.open(API_CACHE_NAME);
+ const cachedResponse = await cache.match(request);
+
+ if (cachedResponse) {
+ const age = Date.now() - new Date(cachedResponse.headers.get('date')).getTime();
+ if (age < API_MAX_AGE) {
+ console.debug(`SW: Cache HIT for ${request.url}`);
+ return cachedResponse;
+ }
+
+ // Cache is too old, fetch a fresh copy
+ cache.delete(request);
+ }
+
+ try {
+ const netResponse = await fetch(request);
+
+ const responseToCache = netResponse.clone();
+
+ cache.put(request, responseToCache);
+
+ console.debug(`SW: Cache MISS for ${request.url}`);
+
+ return netResponse;
+ } catch (error) {
+ throw error;
+ }
+} \ No newline at end of file