artable/src/pages/chatapi/sendMessage.ts
2023-05-19 21:15:28 +07:00

42 lines
1.5 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 { getSessionUser, userAllowedToChat, createChatMessage } 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 chatId = formData.get("chatId");
const message = formData.get("message");
if (chatId === null || message === null) {
throw new Error("Не предоставлены данные отправки сообщения");
}
const userAllowed = await userAllowedToChat(user.id, chatId.toString());
if (!userAllowed) {
throw new Error("Нет доступа к чату");
}
await createChatMessage(chatId.toString(), user.id, message.toString());
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),
};
}