// 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) => `
| ${esc(p.name)} | ${esc(p.phone)} | ${formatBirthDate(p.birthDate)} |
`)
.join("");
return page(
"Пациенты",
`Пациенты
| Имя | Телефон | Дата рождения |
${rows}
Новый пациент
`,
);
}
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("Улыбка", 'Улыбка
Картотека')) },
{ 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("Ошибка", `${Object.values(errors).map(esc).join("
")}
Назад`), 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));
},
},
];