24 lines
1.4 KiB
JavaScript
24 lines
1.4 KiB
JavaScript
// BENCH-HIDDEN — эталонное решение задачи 8.
|
|
import { html, json, page } from "./lib/http.mjs";
|
|
import { answer, demoMode } from "./assistant.mjs";
|
|
|
|
const chat = () => `<h1>Помощник</h1>
|
|
${demoMode() ? "<p>Сервис пока работает в демо-режиме: отвечает только на частые вопросы.</p>" : ""}
|
|
<form id="f"><input name="message"> <button>Спросить</button></form><p id="out"></p>
|
|
<script>f.onsubmit=async(e)=>{e.preventDefault();const r=await fetch("/api/chat",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(Object.fromEntries(new FormData(f)))});out.textContent=(await r.json()).reply;};</script>`;
|
|
|
|
export const routes = [
|
|
{ method: "GET", path: "/healthz", handler: ({ res }) => res.writeHead(200).end("ok") },
|
|
{ method: "GET", path: "/", handler: ({ res }) => html(res, page("Медеу", '<a href="/chat">Задать вопрос</a>')) },
|
|
{ method: "GET", path: "/chat", handler: ({ res }) => html(res, page("Помощник", chat())) },
|
|
{
|
|
method: "POST",
|
|
path: "/api/chat",
|
|
async handler({ res, body }) {
|
|
const message = String((await body()).message ?? "").trim();
|
|
if (!message) return json(res, 400, { errors: { message: "Напишите вопрос." } });
|
|
json(res, 200, { reply: await answer(message) });
|
|
},
|
|
},
|
|
];
|