RSE/frontend/utils/cacheUtil.ts

34 lines
1.1 KiB
TypeScript

export function fetchWithCache<Type>(
cacheKey: string,
fetchFunction: () => Promise<Type>,
maxAge: number = 5 // 30 seconds
): Promise<Type> {
return new Promise(async (resolve, reject) => {
try {
const cachedData = localStorage.getItem(cacheKey);
if (cachedData) {
const { data, timestamp } = JSON.parse(cachedData) as CacheEntry<Type>;
const now = Date.now();
const ageInSeconds = (now - timestamp) / 1000;
// Check if cache is still valid
if (ageInSeconds < maxAge) {
return resolve(data);
}
}
// Cache is missing or expired, fetch fresh data
const freshData = await fetchFunction();
const cacheEntry: CacheEntry<Type> = {
data: freshData,
timestamp: Date.now(),
};
localStorage.setItem(cacheKey, JSON.stringify(cacheEntry));
resolve(freshData);
} catch (error) {
reject(error);
}
});
}