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

55 lines
2.1 KiB
JavaScript

// BENCH-HIDDEN — эталонное решение задачи 4.
import { esc, html, json, page } from "./lib/http.mjs";
import { addPatient, formatBirthDate, listPatients, validatePatient } from "./patients.mjs";
function patientsPage() {
const rows = listPatients()
.map((p) => `<tr><td>${esc(p.name)}</td><td>${esc(p.phone)}</td><td>${formatBirthDate(p.birthDate)}</td></tr>`)
.join("");
return page(
"Пациенты",
`<h1>Пациенты</h1>
<table><thead><tr><th>Имя</th><th>Телефон</th><th>Дата рождения</th></tr></thead><tbody>${rows}</tbody></table>
<h2>Новый пациент</h2>
<form method="post" action="/patients">
<label>Имя и фамилия <input name="name"></label>
<label>Телефон <input name="phone"></label>
<label>Дата рождения <input name="birthDate" type="date"></label>
<button>Добавить</button>
</form>`,
);
}
export const routes = [
{
method: "GET",
path: "/healthz",
handler: ({ res }) => {
res.writeHead(200, { "content-type": "text/plain; charset=utf-8" });
res.end("ok");
},
},
{ method: "GET", path: "/", handler: ({ res }) => html(res, page("Улыбка", '<h1>Улыбка</h1><a href="/patients">Картотека</a>')) },
{ method: "GET", path: "/patients", handler: ({ res }) => html(res, patientsPage()) },
{
method: "POST",
path: "/patients",
async handler({ res, body }) {
const { errors, value } = validatePatient(await body());
if (Object.keys(errors).length) return html(res, page("Ошибка", `<p>${Object.values(errors).map(esc).join("<br>")}</p><a href="/patients">Назад</a>`), 400);
addPatient(value);
res.writeHead(303, { location: "/patients" }).end();
},
},
{ method: "GET", path: "/api/patients", handler: ({ res }) => json(res, 200, listPatients()) },
{
method: "POST",
path: "/api/patients",
async handler({ res, body }) {
const { errors, value } = validatePatient(await body());
if (Object.keys(errors).length) return json(res, 400, { errors });
json(res, 201, addPatient(value));
},
},
];