// ECB daily reference rates (EUR-based). Fetched by the server so that // clients never contact a third party (SPEC.md §8.2). import type { Store } from './db.ts'; /** Parse the ECB eurofxref XML into date → { currency: rate }. EUR = "1". */ export function parseEcbXml(xml: string): Map> { const out = new Map>(); const dayRe = /([\s\S]*?)<\/Cube>/g; const rateRe = //g; for (const day of xml.matchAll(dayRe)) { const rates: Record = { EUR: '1' }; for (const r of day[2].matchAll(rateRe)) rates[r[1]] = r[2]; out.set(day[1], rates); } return out; } export class RatesService { private timer: NodeJS.Timeout | undefined; private readonly store: Store; private readonly baseUrl: string; constructor(store: Store, baseUrl: string) { this.store = store; this.baseUrl = baseUrl; } async refresh(): Promise { // Full history the first time (≈8 MB), the last 90 days afterwards. const file = this.store.latestRatesDate() ? 'eurofxref-hist-90d.xml' : 'eurofxref-hist.xml'; const res = await fetch(`${this.baseUrl}/${file}`, { signal: AbortSignal.timeout(60_000) }); if (!res.ok) throw new Error(`ECB ${file}: HTTP ${res.status}`); const days = parseEcbXml(await res.text()); if (days.size === 0) throw new Error(`ECB ${file}: no rates parsed`); this.store.tx(() => { for (const [date, rates] of days) this.store.saveRates(date, rates); }); console.log(`rates: stored ${days.size} days from ${file}, latest ${this.store.latestRatesDate()}`); } /** Refresh now and then every 6 hours (ECB publishes once a day ~16:00 CET). */ start(): void { const run = () => this.refresh().catch((e) => console.error(`rates: ${e.message}`)); void run(); this.timer = setInterval(run, 6 * 3600_000); this.timer.unref(); } stop(): void { clearInterval(this.timer); } }