Files
led-controller/web/static/fetch_cache.js
jimmyandClaude Sonnet 5.5 38162d4b89 feat: faster, correct preset editor; default presets use their own pattern
- Editing a preset can change its pattern (the dropdown was disabled).
- on, off and rainbow are built-in patterns and are always listed, so the
  editor no longer falls back to the first pattern (aurora) for them.
- The editor loads the pattern names once and only the selected pattern's
  definition (new GET /patterns/names and GET /patterns/<name>).
- A shared GET cache (fetch_cache.js) reuses profile, palette, zone, preset,
  group and pattern lookups; any write clears it and entries expire at 30 s.
- The seeded rainbow preset uses the rainbow pattern.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-10 01:46:11 +13:00

46 lines
1.7 KiB
JavaScript

// Page-wide cache for the GET requests the editors repeat (profile, palette, zones, presets,
// groups, patterns). Any write (POST/PUT/PATCH/DELETE) empties it, entries expire after TTL_MS,
// and a request with cache: 'no-store' always goes to the controller. Live data (/devices,
// /status, /settings, ...) is never cached.
(function () {
const CACHEABLE = /^\/(profiles\/current|palettes|patterns|presets|zones|groups)(\/|\?|$)/;
const TTL_MS = 30000;
const store = new Map(); // url -> { at, promise }
const nativeFetch = window.fetch.bind(window);
const pathOf = (input) => {
try {
const u = new URL(typeof input === 'string' ? input : input.url, location.origin);
return u.origin === location.origin ? u.pathname + u.search : null;
} catch (_) {
return null;
}
};
window.fetch = function (input, init) {
const method = String((init && init.method) || (input && input.method) || 'GET').toUpperCase();
if (method !== 'GET') {
store.clear();
return nativeFetch(input, init).finally(() => store.clear());
}
const path = pathOf(input);
const noStore = (init && init.cache === 'no-store') || (input && input.cache === 'no-store');
if (!path || noStore || !CACHEABLE.test(path)) {
return nativeFetch(input, init);
}
const hit = store.get(path);
if (hit && Date.now() - hit.at < TTL_MS) {
return hit.promise.then((r) => r.clone());
}
const promise = nativeFetch(input, init).then((r) => {
if (!r.ok) store.delete(path); // never keep an error
return r;
}, (e) => {
store.delete(path);
throw e;
});
store.set(path, { at: Date.now(), promise });
return promise.then((r) => r.clone());
};
})();