forked from mtusi2026/mtusi2026lab2
60 lines
2.7 KiB
TypeScript
60 lines
2.7 KiB
TypeScript
import type { Chat, Page, User } from '../domain/models';
|
|
import { invalidRequest, notFound } from '../errors/api-error';
|
|
import { db, transaction } from '../repositories/postgres';
|
|
import { parseWith } from '../validation/parse';
|
|
import { createChatSchema, uuidSchema } from '../validation/schemas';
|
|
import { makePage, parsePage } from './cursor.service';
|
|
|
|
const chatFields = `
|
|
c.id, c.title, c.created_at,
|
|
ARRAY(SELECT user_id FROM chat_members
|
|
WHERE chat_id = c.id ORDER BY position) AS member_ids
|
|
`;
|
|
|
|
export async function createChat(actor: User, input: unknown): Promise<Chat> {
|
|
const { title, member_ids } = parseWith(createChatSchema, input);
|
|
if (!member_ids.includes(actor.id)) {
|
|
throw invalidRequest('Текущий пользователь должен входить в member_ids');
|
|
}
|
|
return transaction(async (client) => {
|
|
const ids = await client.query('SELECT id FROM users WHERE id = ANY($1::uuid[])', [member_ids]);
|
|
if (ids.rowCount !== member_ids.length) {
|
|
throw invalidRequest('member_ids содержит неизвестного пользователя');
|
|
}
|
|
const { rows } = await client.query<Omit<Chat, 'member_ids'>>(
|
|
'INSERT INTO chats (title) VALUES ($1) RETURNING id, title, created_at', [title],
|
|
);
|
|
const chat = rows[0];
|
|
if (!chat) throw new Error('Chat not returned');
|
|
await client.query(
|
|
`INSERT INTO chat_members (chat_id, user_id, position)
|
|
SELECT $1, id, position FROM unnest($2::uuid[]) WITH ORDINALITY AS m(id, position)`,
|
|
[chat.id, member_ids],
|
|
);
|
|
return { ...chat, member_ids };
|
|
});
|
|
}
|
|
|
|
export async function requireAccessibleChat(actor: User, chatId: string): Promise<Chat> {
|
|
const id = parseWith(uuidSchema, chatId);
|
|
const { rows } = await db.query<Chat>(
|
|
`SELECT ${chatFields} FROM chats c JOIN chat_members m ON m.chat_id = c.id
|
|
WHERE c.id = $1 AND m.user_id = $2`,
|
|
[id, actor.id],
|
|
);
|
|
if (!rows[0]) throw notFound();
|
|
return rows[0];
|
|
}
|
|
|
|
export async function listChats(actor: User, limit: unknown, cursor: unknown): Promise<Page<Chat>> {
|
|
const scope = { kind: 'chats', resource: actor.id } as const;
|
|
const page = parsePage(limit, cursor, scope);
|
|
const { rows } = await db.query<Chat>(
|
|
`SELECT ${chatFields} FROM chats c JOIN chat_members m ON m.chat_id = c.id
|
|
WHERE m.user_id = $1 AND ($2::timestamptz IS NULL OR (c.created_at, c.id) > ($2, $3))
|
|
ORDER BY c.created_at, c.id LIMIT $4`,
|
|
[actor.id, page.after?.created_at, page.after?.id, page.limit + 1],
|
|
);
|
|
return makePage(rows, page.limit, scope);
|
|
}
|