Files
PromptTech/frontend/src/utils/apiCache.js

57 lines
1.2 KiB
JavaScript
Raw Normal View History

2026-01-27 18:07:00 -06:00
// Simple in-memory cache for API responses
const cache = new Map();
const CACHE_DURATION = 30000; // 30 seconds (reduced from 60)
2026-01-27 18:07:00 -06:00
export const getCached = (key) => {
const cached = cache.get(key);
if (!cached) return null;
const isExpired = Date.now() - cached.timestamp > CACHE_DURATION;
if (isExpired) {
cache.delete(key);
return null;
}
return cached.data;
};
export const setCache = (key, data) => {
cache.set(key, {
data,
timestamp: Date.now(),
});
};
export const clearCache = (key) => {
if (key) {
// If key ends with a dash, clear all keys starting with that prefix
if (key.endsWith("-")) {
const prefix = key;
const keysToDelete = [];
for (const [cacheKey] of cache) {
if (cacheKey.startsWith(prefix)) {
keysToDelete.push(cacheKey);
}
}
keysToDelete.forEach((k) => cache.delete(k));
} else {
cache.delete(key);
}
2026-01-27 18:07:00 -06:00
} else {
cache.clear();
}
};
// Debounce function for API calls
export const debounce = (func, wait) => {
let timeout;
return function executedFunction(...args) {
const later = () => {
clearTimeout(timeout);
func(...args);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
};