|
| 1 | +import { store } from './store' |
| 2 | + |
| 3 | +const CACHE_TTL = 1000 * 60 * 60 |
| 4 | + |
| 5 | +interface CurrencyRatesApiResponse { |
| 6 | + result?: string |
| 7 | + rates?: Record<string, number> |
| 8 | + time_last_update_unix?: number |
| 9 | +} |
| 10 | + |
| 11 | +export interface CurrencyRatesPayload { |
| 12 | + rates: Record<string, number> |
| 13 | + fetchedAt: number |
| 14 | + source: 'live' | 'cache' | 'unavailable' |
| 15 | +} |
| 16 | + |
| 17 | +function normalizeRates(rates: Record<string, number>) { |
| 18 | + const normalized: Record<string, number> = { USD: 1 } |
| 19 | + |
| 20 | + Object.entries(rates).forEach(([code, value]) => { |
| 21 | + if (typeof value === 'number' && Number.isFinite(value)) { |
| 22 | + normalized[code] = value |
| 23 | + } |
| 24 | + }) |
| 25 | + |
| 26 | + normalized.USD = 1 |
| 27 | + |
| 28 | + return normalized |
| 29 | +} |
| 30 | + |
| 31 | +export async function getCurrencyRates(): Promise<CurrencyRatesPayload> { |
| 32 | + const cached = store.currencyRates.get('cache') |
| 33 | + |
| 34 | + if (cached && Date.now() - cached.fetchedAt < CACHE_TTL) { |
| 35 | + return { |
| 36 | + ...cached, |
| 37 | + source: 'cache', |
| 38 | + } |
| 39 | + } |
| 40 | + |
| 41 | + try { |
| 42 | + const response = await fetch('https://open.er-api.com/v6/latest/USD') |
| 43 | + if (!response.ok) { |
| 44 | + throw new Error( |
| 45 | + `Currency rates request failed with status ${response.status}`, |
| 46 | + ) |
| 47 | + } |
| 48 | + |
| 49 | + const data = (await response.json()) as CurrencyRatesApiResponse |
| 50 | + if (data.result !== 'success' || !data.rates) { |
| 51 | + throw new Error('Currency rates response is invalid') |
| 52 | + } |
| 53 | + |
| 54 | + const payload = { |
| 55 | + rates: normalizeRates(data.rates), |
| 56 | + fetchedAt: data.time_last_update_unix |
| 57 | + ? data.time_last_update_unix * 1000 |
| 58 | + : Date.now(), |
| 59 | + } |
| 60 | + |
| 61 | + store.currencyRates.set('cache', payload) |
| 62 | + |
| 63 | + return { |
| 64 | + ...payload, |
| 65 | + source: 'live', |
| 66 | + } |
| 67 | + } |
| 68 | + catch { |
| 69 | + if (cached) { |
| 70 | + return { |
| 71 | + ...cached, |
| 72 | + source: 'cache', |
| 73 | + } |
| 74 | + } |
| 75 | + |
| 76 | + return { |
| 77 | + rates: {}, |
| 78 | + fetchedAt: 0, |
| 79 | + source: 'unavailable', |
| 80 | + } |
| 81 | + } |
| 82 | +} |
0 commit comments