artable/src/pages/userapi/updateUserLore.ts

44 lines
1.6 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.

import type { APIContext } from "astro";
import { updateUserLore, getSessionUser } from "../../db";
import { Prisma } from "@prisma/client";
export async function post({ request, cookies }: APIContext) {
const response: { ok: boolean; reason?: string } = {
ok: true,
};
try {
const sessId = cookies.get("session").value!;
const user = (await getSessionUser(sessId))!;
const formData = await request.formData();
const login = formData.get("login");
const userLore = formData.get("userLore");
if (login === null || userLore === null) {
throw new Error("Не предоставлены данные для обновления информации");
}
if (user.login !== login.toString()) {
throw new Error("Доступно только этому пользователю");
}
const updatedUser = await updateUserLore(login.toString(), userLore.toString());
if (updatedUser === null) {
throw new Error("Не удалось обновить информацию");
}
response.ok = true;
} catch (e: any) {
response.ok = false;
if (e instanceof Prisma.PrismaClientKnownRequestError) {
response.reason = `Неизвестная ошибка базы данных. Код ${e.code}`;
} else if (e instanceof Error) {
response.reason = e.message.trim();
} else {
response.reason = e.toString().trim();
}
}
return {
body: JSON.stringify(response),
};
}