Добавил систему чатов
This commit is contained in:
parent
be1d03b459
commit
f2a6469a55
10 changed files with 632 additions and 7 deletions
42
src/pages/chatapi/sendMessage.ts
Normal file
42
src/pages/chatapi/sendMessage.ts
Normal 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),
|
||||
};
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue