From 1bd44e6632a69771c13647a7756556e63ec708d8 Mon Sep 17 00:00:00 2001 From: Alexander Schmidt Date: Sat, 7 Feb 2026 13:25:38 +0100 Subject: [PATCH] feat: cache categories in localStorage for 24h to reduce API requests --- js/services/categories.js | 30 +++++++++++++++++++++++++++++- js/services/directus.js | 10 ++++++++-- 2 files changed, 37 insertions(+), 3 deletions(-) diff --git a/js/services/categories.js b/js/services/categories.js index 64642f8..b6054f1 100644 --- a/js/services/categories.js +++ b/js/services/categories.js @@ -9,8 +9,33 @@ class CategoriesService { constructor() { this.cache = null this.cacheTimestamp = 0 - this.cacheTimeout = 10 * 60 * 1000 // 10 minutes + this.cacheTimeout = 24 * 60 * 60 * 1000 // 24 hours + this.storageKey = 'dgray_categories' + this.storageTimestampKey = 'dgray_categories_ts' this._pending = null + this._loadFromStorage() + } + + _loadFromStorage() { + try { + const data = localStorage.getItem(this.storageKey) + const ts = parseInt(localStorage.getItem(this.storageTimestampKey) || '0', 10) + if (data && ts && Date.now() - ts < this.cacheTimeout) { + this.cache = JSON.parse(data) + this.cacheTimestamp = ts + } + } catch (e) { + // ignore corrupt storage + } + } + + _saveToStorage() { + try { + localStorage.setItem(this.storageKey, JSON.stringify(this.cache)) + localStorage.setItem(this.storageTimestampKey, String(this.cacheTimestamp)) + } catch (e) { + // storage full or unavailable + } } async getAll() { @@ -23,6 +48,7 @@ class CategoriesService { this._pending = directus.getCategories().then(categories => { this.cache = categories this.cacheTimestamp = Date.now() + this._saveToStorage() this._pending = null return categories }).catch(err => { @@ -167,6 +193,8 @@ class CategoriesService { clearCache() { this.cache = null this.cacheTimestamp = 0 + localStorage.removeItem(this.storageKey) + localStorage.removeItem(this.storageTimestampKey) } } diff --git a/js/services/directus.js b/js/services/directus.js index d928b8e..28eb134 100644 --- a/js/services/directus.js +++ b/js/services/directus.js @@ -164,8 +164,14 @@ class DirectusService { } if (response.status === 429 && _retryCount < 3) { - const retryAfter = parseInt(response.headers.get('Retry-After') || '3', 10) - await new Promise(r => setTimeout(r, retryAfter * 1000)) + const retryAfterHeader = response.headers.get('Retry-After') || '1' + let waitMs + if (parseInt(retryAfterHeader, 10) > 100) { + waitMs = parseInt(retryAfterHeader, 10) + } else { + waitMs = parseInt(retryAfterHeader, 10) * 1000 + } + await new Promise(r => setTimeout(r, waitMs)) return this.request(endpoint, options, _retryCount + 1) }