// BENCH-HIDDEN — эталонное решение задачи 5. import { html, json, page } from "./lib/http.mjs"; import { CURRENCIES, RatesUnavailable, getRates } from "./rates.mjs"; const DOWN = "Курсы временно недоступны, попробуйте через несколько минут"; const calc = `

Калькулятор обмена

Считаем по курсу «Курсы KZ».

`; export const routes = [ { method: "GET", path: "/healthz", handler: ({ res }) => res.writeHead(200).end("ok") }, { method: "GET", path: "/", handler: ({ res }) => html(res, page("Достык", 'Калькулятор обмена')) }, { method: "GET", path: "/convert", handler: ({ res }) => html(res, page("Калькулятор обмена", calc)) }, { method: "GET", path: "/api/convert", async handler({ res, query }) { const amount = Number(query.amount); const to = String(query.to ?? "").toUpperCase(); const errors = {}; if (!(amount > 0) || amount > 10_000_000) errors.amount = "Введите сумму от 1 до 10 000 000 ₸."; if (!CURRENCIES.includes(to)) errors.to = "Выберите доллар, евро или рубль."; if (Object.keys(errors).length) return json(res, 400, { errors }); try { const rate = (await getRates())[to]; json(res, 200, { amount, to, rate, result: Math.round(amount * rate * 100) / 100 }); } catch (e) { if (e instanceof RatesUnavailable) return json(res, 503, { errors: { rates: DOWN } }); throw e; } }, }, ];