peppa/bench/tasks/05-external-api/solution/product/routes.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

43 lines
2.1 KiB
JavaScript

// BENCH-HIDDEN — эталонное решение задачи 5.
import { html, json, page } from "./lib/http.mjs";
import { CURRENCIES, RatesUnavailable, getRates } from "./rates.mjs";
const DOWN = "Курсы временно недоступны, попробуйте через несколько минут";
const calc = `<h1>Калькулятор обмена</h1>
<form id="f"><input name="amount" type="number"> <select name="to">${CURRENCIES.map((c) => `<option>${c}</option>`).join("")}</select> <button>Посчитать</button></form>
<p id="out">Считаем по курсу «Курсы KZ».</p>
<script>
f.onsubmit = async (e) => {
e.preventDefault();
const q = new URLSearchParams(new FormData(f));
const b = await (await fetch("/api/convert?" + q)).json();
out.textContent = b.errors ? Object.values(b.errors).join(" ") : b.result + " " + b.to + " (курс " + b.rate + ")";
};
</script>`;
export const routes = [
{ method: "GET", path: "/healthz", handler: ({ res }) => res.writeHead(200).end("ok") },
{ method: "GET", path: "/", handler: ({ res }) => html(res, page("Достык", '<a href="/convert">Калькулятор обмена</a>')) },
{ 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;
}
},
},
];