a Linkat frontend.
at main 39 lines 1.1 kB view raw
1/** 2 * Caches data in localStorage with a specified expiry time. 3 * @param key The key to store the data under. 4 * @param data The data to store. 5 * @param ttl The time-to-live for the cache in milliseconds (default: 1 hour). 6 */ 7export function setCache<T>(key: string, data: T, ttl: number = 3600000): void { 8 if (typeof window === 'undefined') { 9 return; // Don't cache on the server 10 } 11 const now = new Date().getTime(); 12 const item = { 13 data: data, 14 expiry: now + ttl, 15 }; 16 localStorage.setItem(key, JSON.stringify(item)); 17} 18 19/** 20 * Retrieves data from localStorage if it's not expired. 21 * @param key The key to retrieve the data from. 22 * @returns The cached data, or null if expired or not found. 23 */ 24export function getCache<T>(key: string): T | null { 25 if (typeof window === 'undefined') { 26 return null; // No cache on the server 27 } 28 const itemStr = localStorage.getItem(key); 29 if (!itemStr) { 30 return null; 31 } 32 const item = JSON.parse(itemStr); 33 const now = new Date().getTime(); 34 if (now > item.expiry) { 35 localStorage.removeItem(key); 36 return null; 37 } 38 return item.data; 39}