peppa/apps/web/app/api/feedback/route.ts
Асель 2c396ff007 PEP-143: web form, «Обращения» page, Home card, translations, glossary, help
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-16 11:23:09 +05:00

48 lines
2.3 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// PEP-143: «Сообщить о проблеме» — the form posts text, screenshots and what the page knows
// (multipart: a server action's body is capped at 1 MB, screenshots are bigger).
import { FEEDBACK_MAX_BYTES, FEEDBACK_MAX_SHOTS, PeppaError, submitFeedback } from "@peppa/core";
import { m } from "@peppa/shared/i18n";
import { asWebActor, currentUser, uiMode } from "@/lib/auth";
import { db } from "@/lib/db";
import { getLocale, getT } from "@/lib/i18n";
export const dynamic = "force-dynamic";
const MAX_BODY = FEEDBACK_MAX_SHOTS * FEEDBACK_MAX_BYTES + 512 * 1024;
export async function POST(req: Request) {
const t = await getT();
const fail = (status: number, error: string) => Response.json({ error }, { status });
const me = await currentUser();
if (!me) return fail(401, t("Нужен вход"));
const user = asWebActor(me);
if (Number(req.headers.get("content-length") ?? 0) > MAX_BODY) return fail(413, t("Скриншоты слишком большие. Приложите файлы поменьше."));
let form: FormData;
try {
form = await req.formData();
} catch {
return fail(400, t("Не получилось прочитать форму. Попробуйте ещё раз."));
}
const shots = form.getAll("shots").filter((v): v is File => typeof v !== "string");
let context: Record<string, unknown> = {};
try {
context = JSON.parse(String(form.get("context") ?? "{}")) as Record<string, unknown>;
} catch {}
try {
// Oversized files are refused before their bytes are read into memory.
if (shots.some((s) => s.size > FEEDBACK_MAX_BYTES)) throw new PeppaError(m("Скриншот больше 5 МБ. Приложите файл поменьше."));
const files = await Promise.all(shots.slice(0, FEEDBACK_MAX_SHOTS + 1).map(async (s) => new Uint8Array(await s.arrayBuffer())));
const f = await submitFeedback(db, user, {
text: String(form.get("text") ?? ""),
via: "web",
files,
// The view and the language are the server's knowledge, not the page's claim.
context: { ...context, mode: await uiMode(), locale: await getLocale(), userAgent: req.headers.get("user-agent") ?? undefined },
});
return Response.json({ ok: true, id: f.id });
} catch (e) {
if (e instanceof PeppaError) return fail(400, t.text(e.message));
throw e;
}
}