peppa/bench/tasks/05-external-api/solution/product/rates.mjs
Асель d108197f0f PEP-184: задачи 5–8, тест набора, archive change, память
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 02:09:17 +05:00

21 lines
767 B
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// BENCH-HIDDEN — эталонное решение задачи 5: курсы с кэшем на 10 минут и таймаутом 5 с.
export const CURRENCIES = ["USD", "EUR", "RUB"];
const TTL_MS = 10 * 60_000;
let cache = null;
export class RatesUnavailable extends Error {}
export async function getRates(now = Date.now()) {
if (cache && now - cache.at < TTL_MS) return cache.rates;
try {
const r = await fetch(`${process.env.RATES_API_URL}/v1/latest?base=KZT`, { signal: AbortSignal.timeout(5000) });
if (!r.ok) throw new Error(`status ${r.status}`);
const b = await r.json();
cache = { at: now, rates: b.rates };
return b.rates;
} catch (e) {
if (cache) return cache.rates;
throw new RatesUnavailable(String(e));
}
}