|
| 1 | +import { writable, get } from 'svelte/store'; |
| 2 | +import type { CacheEntry } from '$lib/utils/types'; |
| 3 | + |
| 4 | +export const contributorsStore = writable<Map<string, CacheEntry<unknown>>>(new Map()); |
| 5 | + |
| 6 | +const CACHE_TTL = 60 * 60 * 1000; |
| 7 | + |
| 8 | +export async function fetchWithCache<T>(url: string): Promise<T> { |
| 9 | + const now = Date.now(); |
| 10 | + |
| 11 | + const cache = get(contributorsStore); |
| 12 | + |
| 13 | + const cached = cache.get(url); |
| 14 | + if (cached && cached.expiresAt > now) { |
| 15 | + console.log('Fetching data from store'); |
| 16 | + return cached.data as T; |
| 17 | + } |
| 18 | + |
| 19 | + console.log('Fetching data from API'); |
| 20 | + |
| 21 | + const response = await fetch(url); |
| 22 | + |
| 23 | + const rateLimit = response.headers.get('X-RateLimit-Limit'); |
| 24 | + const rateRemaining = response.headers.get('X-RateLimit-Remaining'); |
| 25 | + const resetTime = response.headers.get('X-RateLimit-Reset'); |
| 26 | + |
| 27 | + if (rateLimit && rateRemaining) { |
| 28 | + console.log( |
| 29 | + `Rate limit: ${rateLimit}, Remaining: ${rateRemaining} ${new Date(Date.now()).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}` |
| 30 | + ); |
| 31 | + } |
| 32 | + |
| 33 | + if (resetTime) { |
| 34 | + const resetDate = new Date(parseInt(resetTime) * 1000); |
| 35 | + console.log(`Rate limit resets at: ${resetDate}`); |
| 36 | + } |
| 37 | + |
| 38 | + if (!response.ok) { |
| 39 | + console.error(`Failed to fetch from ${url}:`, response.statusText); |
| 40 | + throw new Error(`Failed to fetch from ${url}`); |
| 41 | + } |
| 42 | + |
| 43 | + const data = await response.json(); |
| 44 | + |
| 45 | + contributorsStore.update((currentCache) => { |
| 46 | + currentCache.set(url, { data, expiresAt: now + CACHE_TTL }); |
| 47 | + return new Map(currentCache); |
| 48 | + }); |
| 49 | + |
| 50 | + return data; |
| 51 | +} |
0 commit comments