Добавил систему чатов

This commit is contained in:
Artem VV 2023-05-19 21:15:28 +07:00
parent be1d03b459
commit f2a6469a55
10 changed files with 632 additions and 7 deletions

View file

@ -0,0 +1,42 @@
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),
};
}