132 lines
3.7 KiB
TypeScript
132 lines
3.7 KiB
TypeScript
import { Injectable } from '@nestjs/common';
|
|
import { Prisma } from '@prisma/client';
|
|
import { decodeChatCursor, encodeChatCursor } from '../common/cursor';
|
|
import { Chat } from '../common/domain';
|
|
import { ApiError } from '../common/filters/api-error';
|
|
import { validate as isUuid } from '../common/uuid';
|
|
import { PrismaService, isForeignKeyViolation } from '../db/prisma.service';
|
|
import { ChatPageResponse, toChatResponse } from './dto/chat.response';
|
|
|
|
interface ChatRow {
|
|
id: string;
|
|
title: string;
|
|
createdAt: Date;
|
|
memberIds: string[];
|
|
}
|
|
|
|
@Injectable()
|
|
export class ChatsService {
|
|
constructor(private readonly prisma: PrismaService) {}
|
|
|
|
async create(
|
|
title: string,
|
|
rawMemberIds: string[],
|
|
callerId: string,
|
|
): Promise<Chat> {
|
|
const invalid = rawMemberIds.find((id) => !isUuid(id));
|
|
if (invalid) {
|
|
throw new ApiError('invalid_request', `unknown member_id: ${invalid}`);
|
|
}
|
|
const memberIds = rawMemberIds.map((id) => id.toLowerCase());
|
|
if (new Set(memberIds).size !== memberIds.length) {
|
|
throw new ApiError(
|
|
'invalid_request',
|
|
"All member_ids's elements must be unique",
|
|
);
|
|
}
|
|
if (!memberIds.includes(callerId)) {
|
|
throw new ApiError(
|
|
'invalid_request',
|
|
'member_ids must include the caller',
|
|
);
|
|
}
|
|
try {
|
|
const chat = await this.prisma.$transaction(async (tx) => {
|
|
const created = await tx.chat.create({
|
|
data: { title: title.trim() },
|
|
});
|
|
await tx.chatMember.createMany({
|
|
data: memberIds.map((userId) => ({
|
|
chatId: created.id,
|
|
userId,
|
|
})),
|
|
});
|
|
return created;
|
|
});
|
|
return toChat({ ...chat, memberIds });
|
|
} catch (error) {
|
|
if (isForeignKeyViolation(error)) {
|
|
throw new ApiError(
|
|
'invalid_request',
|
|
'member_ids contain an unknown user',
|
|
);
|
|
}
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
async getForMember(chatId: string, callerId: string): Promise<Chat> {
|
|
if (!isUuid(chatId)) {
|
|
throw new ApiError('invalid_request', 'chatId must be a valid UUID');
|
|
}
|
|
const chat = await this.prisma.chat.findFirst({
|
|
where: { id: chatId, members: { some: { userId: callerId } } },
|
|
include: { members: { select: { userId: true } } },
|
|
});
|
|
if (!chat) {
|
|
throw new ApiError('not_found', 'chat not found');
|
|
}
|
|
return toChat({
|
|
...chat,
|
|
memberIds: chat.members.map((m) => m.userId),
|
|
});
|
|
}
|
|
|
|
async listForMember(
|
|
callerId: string,
|
|
limit: number,
|
|
rawCursor: string | null,
|
|
): Promise<ChatPageResponse> {
|
|
let after = Prisma.empty;
|
|
if (rawCursor !== null) {
|
|
const cursor = decodeChatCursor(rawCursor);
|
|
const member = cursor
|
|
? await this.prisma.chatMember.findUnique({
|
|
where: {
|
|
chatId_userId: { chatId: cursor.id, userId: callerId },
|
|
},
|
|
include: { chat: { select: { createdAt: true } } },
|
|
})
|
|
: null;
|
|
if (!member) {
|
|
throw new ApiError('invalid_request', 'invalid cursor');
|
|
}
|
|
after = Prisma.sql`AND (c.created_at, c.id) > (${member.chat.createdAt}::timestamptz, ${member.chatId}::uuid)`;
|
|
}
|
|
const rows = await this.prisma.$queryRaw<ChatRow[]>`
|
|
SELECT c.id, c.title, c.created_at AS "createdAt",
|
|
ARRAY(SELECT m.user_id::text FROM chat_members m WHERE m.chat_id = c.id) AS "memberIds"
|
|
FROM chat_members cm
|
|
JOIN chats c ON c.id = cm.chat_id
|
|
WHERE cm.user_id = ${callerId}::uuid ${after}
|
|
ORDER BY c.created_at, c.id
|
|
LIMIT ${limit + 1}`;
|
|
const items = rows.slice(0, limit).map(toChat);
|
|
const last = items[items.length - 1];
|
|
return {
|
|
items: items.map(toChatResponse),
|
|
next_cursor:
|
|
rows.length > limit ? encodeChatCursor({ id: last.id }) : null,
|
|
};
|
|
}
|
|
}
|
|
|
|
function toChat(row: ChatRow): Chat {
|
|
return {
|
|
id: row.id,
|
|
title: row.title,
|
|
memberIds: row.memberIds,
|
|
createdAt: row.createdAt.toISOString(),
|
|
};
|
|
}
|