107 lines
3.0 KiB
TypeScript
107 lines
3.0 KiB
TypeScript
import { Injectable } from '@nestjs/common';
|
|
import { Prisma } from '@prisma/client';
|
|
import { codePointLength } from '../common/dto/code-point-length.validator';
|
|
import { decodeMessageCursor, encodeMessageCursor } from '../common/cursor';
|
|
import { Message } from '../common/domain';
|
|
import { ApiError } from '../common/filters/api-error';
|
|
import { validate as isUuid } from '../common/uuid';
|
|
import { PrismaService } from '../db/prisma.service';
|
|
import { MessagePageResponse, toMessageResponse } from './dto/message.response';
|
|
|
|
interface MessageRow {
|
|
id: string;
|
|
chatId: string;
|
|
senderId: string;
|
|
text: string;
|
|
createdAt: Date;
|
|
}
|
|
|
|
@Injectable()
|
|
export class MessagesService {
|
|
constructor(private readonly prisma: PrismaService) {}
|
|
|
|
async create(
|
|
chatId: string,
|
|
callerId: string,
|
|
text: string,
|
|
): Promise<Message> {
|
|
await this.assertMember(chatId, callerId);
|
|
if (codePointLength(text.trim()) === 0) {
|
|
throw new ApiError(
|
|
'invalid_request',
|
|
'text must not be empty or whitespace-only',
|
|
);
|
|
}
|
|
const row = await this.prisma.message.create({
|
|
data: { chatId, senderId: callerId, text },
|
|
});
|
|
return toMessage(row);
|
|
}
|
|
|
|
async list(
|
|
chatId: string,
|
|
callerId: string,
|
|
limit: number,
|
|
rawCursor: string | null,
|
|
): Promise<MessagePageResponse> {
|
|
await this.assertMember(chatId, callerId);
|
|
let after = Prisma.empty;
|
|
if (rawCursor !== null) {
|
|
const cursor = decodeMessageCursor(rawCursor);
|
|
if (cursor && cursor.chatId !== chatId) {
|
|
throw new ApiError(
|
|
'invalid_request',
|
|
'cursor belongs to a different chat',
|
|
);
|
|
}
|
|
const anchor = cursor
|
|
? await this.prisma.message.findFirst({
|
|
where: { id: cursor.id, chatId },
|
|
select: { id: true, createdAt: true },
|
|
})
|
|
: null;
|
|
if (!anchor) {
|
|
throw new ApiError('invalid_request', 'invalid cursor');
|
|
}
|
|
after = Prisma.sql`AND (created_at, id) > (${anchor.createdAt}::timestamptz, ${anchor.id}::uuid)`;
|
|
}
|
|
const rows = await this.prisma.$queryRaw<MessageRow[]>`
|
|
SELECT id, chat_id AS "chatId", sender_id AS "senderId", text, created_at AS "createdAt"
|
|
FROM messages
|
|
WHERE chat_id = ${chatId}::uuid ${after}
|
|
ORDER BY created_at, id
|
|
LIMIT ${limit + 1}`;
|
|
const items = rows.slice(0, limit).map(toMessage);
|
|
const last = items[items.length - 1];
|
|
return {
|
|
items: items.map(toMessageResponse),
|
|
next_cursor:
|
|
rows.length > limit
|
|
? encodeMessageCursor({ chatId, id: last.id })
|
|
: null,
|
|
};
|
|
}
|
|
|
|
private async assertMember(chatId: string, callerId: string): Promise<void> {
|
|
if (!isUuid(chatId)) {
|
|
throw new ApiError('invalid_request', 'chatId must be a valid UUID');
|
|
}
|
|
const member = await this.prisma.chatMember.findUnique({
|
|
where: { chatId_userId: { chatId, userId: callerId } },
|
|
});
|
|
if (!member) {
|
|
throw new ApiError('not_found', 'chat not found');
|
|
}
|
|
}
|
|
}
|
|
|
|
function toMessage(row: MessageRow): Message {
|
|
return {
|
|
id: row.id,
|
|
chatId: row.chatId,
|
|
senderId: row.senderId,
|
|
text: row.text,
|
|
createdAt: row.createdAt.toISOString(),
|
|
};
|
|
}
|