// 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 = `

Запись на пробный урок

`; 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: "/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("Заявки", `

Заявки

${signups.all().map((s) => ``).join("")}
${esc(s.childName)}${esc(s.phone)}${s.age}
`)), }, ];