// BENCH-HIDDEN — эталонное решение задачи 7. import { esc, html, json, page } from "./lib/http.mjs"; import { collection } from "./lib/store.mjs"; const reviews = collection("reviews"); function validate(b) { const errors = {}; const name = String(b.name ?? "").trim(); const text = String(b.text ?? "").trim(); const rating = Number(b.rating); if (!name) errors.name = "Укажите имя."; if (!text || text.length > 1000) errors.text = "Напишите отзыв, до 1000 знаков."; if (!Number.isInteger(rating) || rating < 1 || rating > 5) errors.rating = "Поставьте оценку от 1 до 5."; return { errors, value: { name, text, rating, approved: false } }; } function publicPage() { const list = reviews.all().filter((r) => r.approved); const avg = list.length ? (list.reduce((s, r) => s + r.rating, 0) / list.length).toFixed(1).replace(".", ",") : "—"; return page("Отзывы", `

Отзывы

Средняя оценка: ${avg}

${list.map((r) => `
${"★".repeat(r.rating)} ${esc(r.text)} — ${esc(r.name)}
`).join("")}`); } 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: "/reviews", handler: ({ res }) => html(res, publicPage()) }, { method: "POST", path: "/api/reviews", async handler({ res, body }) { const { errors, value } = validate(await body()); if (Object.keys(errors).length) return json(res, 400, { errors }); json(res, 201, reviews.add(value)); }, }, { method: "GET", path: "/api/reviews", handler: ({ res }) => json(res, 200, reviews.all()) }, { method: "POST", path: "/api/reviews/:id/approve", handler: ({ res, params }) => { const r = reviews.update(params.id, { approved: true }); r ? json(res, 200, r) : json(res, 404, { errors: { id: "Нет такого отзыва." } }); }, }, ];