47 lines
2.1 KiB
JavaScript
47 lines
2.1 KiB
JavaScript
// 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("Отзывы", `<h1>Отзывы</h1><p>Средняя оценка: ${avg}</p>${list.map((r) => `<blockquote>${"★".repeat(r.rating)} ${esc(r.text)} — ${esc(r.name)}</blockquote>`).join("")}`);
|
||
}
|
||
|
||
export const routes = [
|
||
{ method: "GET", path: "/healthz", handler: ({ res }) => res.writeHead(200).end("ok") },
|
||
{ method: "GET", path: "/", handler: ({ res }) => html(res, page("Таба нан", '<a href="/reviews">Отзывы</a>')) },
|
||
{ 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: "Нет такого отзыва." } });
|
||
},
|
||
},
|
||
];
|