aboutsummaryrefslogtreecommitdiff
path: root/src/frontend/public/pwa-worker.js
blob: 649a161b585b16a76d5fcbba6d7c92ba22129987 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
const CACHE_VERSION = "20251118a";
const STATIC_CACHE_NAME = `static-cache-${CACHE_VERSION}`;
const STATIC_CACHE_ASSETS = ["/favicon.ico", "/logo-256.png", "/logo-512.jpg"];

const EXPR_CACHE_AFTER_FIRST_VIEW =
  /(\/assets\/.*)|(\/api\/(vigo|santiago)\/GetStopTimetable.*)/;

const ESTIMATES_MIN_AGE = 15 * 1000;
const ESTIMATES_MAX_AGE = 30 * 1000;

self.addEventListener("install", (event) => {
  event.waitUntil(
    caches
      .open(STATIC_CACHE_NAME)
      .then((cache) => cache.addAll(STATIC_CACHE_ASSETS))
      .then(() => self.skipWaiting())
  );
});

self.addEventListener("activate", (event) => {
  const doCleanup = async () => {
    // Cleans the old caches
    const cacheNames = await caches.keys();
    await Promise.all(
      cacheNames.map((name) => {
        if (name !== STATIC_CACHE_NAME) {
          return caches.delete(name);
        }
      })
    );

    await self.clients.claim();
  };

  event.waitUntil(doCleanup());
});

self.addEventListener("fetch", async (event) => {
  const request = event.request;
  const url = new URL(request.url);

  // Ignore requests with unsupported schemes
  if (!url.protocol.startsWith("http")) {
    return;
  }

  // Navigating => we don't intercept anything, if it fails, good luck
  if (request.mode === "navigate") {
    return;
  }

  // Static => cache first, if not, network; if not, fallback
  const isAssetCacheable =
    STATIC_CACHE_ASSETS.includes(url.pathname) ||
    EXPR_CACHE_AFTER_FIRST_VIEW.test(url.pathname);
  if (request.method === "GET" && isAssetCacheable) {
    const response = handleStaticRequest(request);
    if (response !== null) {
      event.respondWith(response);
    }
    return;
  }
});

async function handleStaticRequest(request) {
  const cache = await caches.open(STATIC_CACHE_NAME);
  const cachedResponse = await cache.match(request);
  if (cachedResponse) {
    return cachedResponse;
  }

  try {
    const netResponse = await fetch(request);
    if (netResponse.ok) cache.put(request, netResponse.clone());
    return netResponse;
  } catch (err) {
    return null;
  }
}