peppa/bench/tasks/02-form/solution/product/routes.mjs
2026-11-17 02:09:17 +05:00

66 lines
3.1 KiB
JavaScript

// BENCH-HIDDEN — эталонное решение задачи 2.
import { esc, html, json, page } from "./lib/http.mjs";
import { collection } from "./lib/store.mjs";
const signups = collection("signups");
export function normalizePhone(raw) {
let d = String(raw ?? "").replace(/[\s()-]/g, "");
if (/^8\d{10}$/.test(d)) d = `+7${d.slice(1)}`;
return /^\+7\d{10}$/.test(d) ? d : null;
}
export function validate(b) {
const errors = {};
const name = String(b.childName ?? "").trim();
if (name.length < 2 || name.length > 50) errors.childName = "Укажите имя ребёнка: от 2 до 50 букв.";
const phone = normalizePhone(b.phone);
if (!phone) errors.phone = "Укажите номер в виде +7 и 10 цифр.";
const age = Number(b.age);
if (!Number.isInteger(age) || age < 6 || age > 14) errors.age = "Мы принимаем детей от 6 до 14 лет.";
return { errors, value: { childName: name, phone, age } };
}
const form = `
<h1>Запись на пробный урок</h1>
<form id="f">
<label>Имя ребёнка <input name="childName"></label><div data-err="childName"></div>
<label>Телефон родителя <input name="phone"></label><div data-err="phone"></div>
<label>Возраст ребёнка <input name="age" type="number"></label><div data-err="age"></div>
<button>Записаться</button>
</form>
<p id="ok" hidden>Спасибо! Мы позвоним вам в течение дня</p>
<script>
f.onsubmit = async (e) => {
e.preventDefault();
const body = Object.fromEntries(new FormData(f));
const r = await fetch("/api/signups", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
document.querySelectorAll("[data-err]").forEach((el) => (el.textContent = ""));
if (r.ok) { f.hidden = true; ok.hidden = false; return; }
const { errors = {} } = await r.json();
for (const [k, v] of Object.entries(errors)) document.querySelector('[data-err="' + k + '"]').textContent = v;
};
</script>`;
export const routes = [
{ method: "GET", path: "/healthz", handler: ({ res }) => res.writeHead(200).end("ok") },
{ method: "GET", path: "/", handler: ({ res }) => html(res, page("Робостарт", '<h1>Робостарт</h1><a href="/signup">Записаться на пробный урок</a>')) },
{ method: "GET", path: "/signup", handler: ({ res }) => html(res, page("Запись на пробный урок", form)) },
{
method: "POST",
path: "/api/signups",
async handler({ res, body }) {
const { errors, value } = validate(await body());
if (Object.keys(errors).length) return json(res, 400, { errors });
json(res, 201, signups.add(value));
},
},
{ method: "GET", path: "/api/signups", handler: ({ res }) => json(res, 200, signups.all()) },
{
method: "GET",
path: "/signups",
handler: ({ res }) =>
html(res, page("Заявки", `<h1>Заявки</h1><table>${signups.all().map((s) => `<tr><td>${esc(s.childName)}</td><td>${esc(s.phone)}</td><td>${s.age}</td></tr>`).join("")}</table>`)),
},
];