All files / src/utils swCache.js

100% Statements 43/43
100% Branches 7/7
100% Functions 1/1
100% Lines 43/43

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 461x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 6x 4x 4x 4x 4x 3x 6x 1x 1x 1x 6x  
/**
 * Service-worker cache busting for writes (SB-902).
 *
 * The service worker serves the read APIs listed in `sw.js` with
 * StaleWhileRevalidate: a GET returns the cached copy immediately and
 * refreshes in the background. That is right for fans, and wrong the instant
 * the same session has just written: an admin POSTs a tournament match, the
 * component re-fetches `/api/tournaments/{id}`, and the SW hands back the
 * response it cached *before* the write. The row only appears after a reload.
 *
 * So: after any successful write, drop the whole runtime cache. The breadth is
 * deliberate. Working out which cached URLs a given write invalidates means
 * re-deriving the backend's own invalidation rules in the client, and getting
 * that wrong reintroduces exactly this bug in a narrower place. Only admins and
 * team managers write, the cache holds nothing but reference/read data, and
 * every entry refills in a single request — there is nothing to be clever with.
 */
 
// Must match the `cacheName` of the runtime routes in src/sw.js.
export const API_CACHE_NAME = 'mt-reference-and-standings-v1';
// Score-bearing reads (standings, tournaments) live in their own NetworkFirst
// cache since SB-908; a write has to drop that one too.
export const RESULTS_CACHE_NAME = 'mt-results-v1';
export const API_CACHE_NAMES = [API_CACHE_NAME, RESULTS_CACHE_NAME];
 
/**
 * Delete the service worker's cached API responses.
 *
 * Safe to call anywhere: no service worker, no Cache API (older browsers,
 * some private-mode contexts), or an already-empty cache are all no-ops.
 *
 * @returns {Promise<boolean>} true if any cache was actually deleted.
 */
export async function bustApiCache() {
  if (typeof caches === 'undefined' || !caches?.delete) return false;
  try {
    const deleted = await Promise.all(
      API_CACHE_NAMES.map(name => caches.delete(name))
    );
    return deleted.some(Boolean);
  } catch {
    // A failed bust must never fail the write that triggered it.
    return false;
  }
}