feat: cache categories in localStorage for 24h to reduce API requests

This commit is contained in:
2026-02-07 13:25:38 +01:00
parent 7e7310e5dd
commit 1bd44e6632
2 changed files with 37 additions and 3 deletions

View File

@@ -9,8 +9,33 @@ class CategoriesService {
constructor() { constructor() {
this.cache = null this.cache = null
this.cacheTimestamp = 0 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._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() { async getAll() {
@@ -23,6 +48,7 @@ class CategoriesService {
this._pending = directus.getCategories().then(categories => { this._pending = directus.getCategories().then(categories => {
this.cache = categories this.cache = categories
this.cacheTimestamp = Date.now() this.cacheTimestamp = Date.now()
this._saveToStorage()
this._pending = null this._pending = null
return categories return categories
}).catch(err => { }).catch(err => {
@@ -167,6 +193,8 @@ class CategoriesService {
clearCache() { clearCache() {
this.cache = null this.cache = null
this.cacheTimestamp = 0 this.cacheTimestamp = 0
localStorage.removeItem(this.storageKey)
localStorage.removeItem(this.storageTimestampKey)
} }
} }

View File

@@ -164,8 +164,14 @@ class DirectusService {
} }
if (response.status === 429 && _retryCount < 3) { if (response.status === 429 && _retryCount < 3) {
const retryAfter = parseInt(response.headers.get('Retry-After') || '3', 10) const retryAfterHeader = response.headers.get('Retry-After') || '1'
await new Promise(r => setTimeout(r, retryAfter * 1000)) 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) return this.request(endpoint, options, _retryCount + 1)
} }