feat: add database and orm
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
import { Message } from '../../common/store/domain';
|
||||
import { Message } from '../../common/domain';
|
||||
|
||||
export interface MessageResponse {
|
||||
id: string;
|
||||
|
||||
@@ -11,7 +11,7 @@ import {
|
||||
import { AuthGuard } from '../common/auth/auth.guard';
|
||||
import { CurrentUser } from '../common/auth/current-user.decorator';
|
||||
import { parseLimit, rawCursorParam } from '../common/dto/pagination-query.dto';
|
||||
import { User } from '../common/store/domain';
|
||||
import { User } from '../common/domain';
|
||||
import { CreateMessageDto } from './dto/create-message.dto';
|
||||
import {
|
||||
MessagePageResponse,
|
||||
@@ -27,22 +27,22 @@ export class MessagesController {
|
||||
|
||||
@Post()
|
||||
@HttpCode(201)
|
||||
create(
|
||||
async create(
|
||||
@Param('chatId') chatId: string,
|
||||
@Body() dto: CreateMessageDto,
|
||||
@CurrentUser() user: User,
|
||||
): MessageResponse {
|
||||
const message = this.messages.create(chatId, user.id, dto.text);
|
||||
): Promise<MessageResponse> {
|
||||
const message = await this.messages.create(chatId, user.id, dto.text);
|
||||
return toMessageResponse(message);
|
||||
}
|
||||
|
||||
@Get()
|
||||
list(
|
||||
async list(
|
||||
@Param('chatId') chatId: string,
|
||||
@CurrentUser() user: User,
|
||||
@Query('limit') limitRaw: unknown,
|
||||
@Query('cursor') cursorRaw: unknown,
|
||||
): MessagePageResponse {
|
||||
): Promise<MessagePageResponse> {
|
||||
const limit = parseLimit(limitRaw);
|
||||
const cursor = rawCursorParam(cursorRaw);
|
||||
return this.messages.list(chatId, user.id, limit, cursor);
|
||||
|
||||
@@ -1,73 +1,106 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { ApiError } from '../common/filters/api-error';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { codePointLength } from '../common/dto/code-point-length.validator';
|
||||
import { Message } from '../common/store/domain';
|
||||
import {
|
||||
decodeMessageCursor,
|
||||
encodeMessageCursor,
|
||||
StoreService,
|
||||
} from '../common/store/store.service';
|
||||
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 store: StoreService) {}
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
create(chatId: string, callerId: string, text: string): Message {
|
||||
this.assertMember(chatId, callerId);
|
||||
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',
|
||||
);
|
||||
}
|
||||
return this.store.createMessage(chatId, callerId, text);
|
||||
const row = await this.prisma.message.create({
|
||||
data: { chatId, senderId: callerId, text },
|
||||
});
|
||||
return toMessage(row);
|
||||
}
|
||||
|
||||
list(
|
||||
async list(
|
||||
chatId: string,
|
||||
callerId: string,
|
||||
limit: number,
|
||||
rawCursor: string | null,
|
||||
): MessagePageResponse {
|
||||
this.assertMember(chatId, callerId);
|
||||
const cursor =
|
||||
rawCursor === null ? null : decodeMessageCursor(rawCursor);
|
||||
if (rawCursor !== null && cursor === null) {
|
||||
throw new ApiError('invalid_request', 'invalid cursor');
|
||||
): 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)`;
|
||||
}
|
||||
if (cursor && cursor.chatId !== chatId) {
|
||||
throw new ApiError(
|
||||
'invalid_request',
|
||||
'cursor belongs to a different chat',
|
||||
);
|
||||
}
|
||||
if (cursor && !this.store.messageCursorExists(chatId, cursor.id)) {
|
||||
throw new ApiError('invalid_request', 'invalid cursor');
|
||||
}
|
||||
const items = this.store.listMessages(chatId, cursor, limit);
|
||||
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];
|
||||
const hasMore = last
|
||||
? this.store.hasMoreMessagesAfter(chatId, last.id)
|
||||
: false;
|
||||
return {
|
||||
items: items.map(toMessageResponse),
|
||||
next_cursor: hasMore
|
||||
? encodeMessageCursor({ chatId, id: last.id })
|
||||
: null,
|
||||
next_cursor:
|
||||
rows.length > limit
|
||||
? encodeMessageCursor({ chatId, id: last.id })
|
||||
: null,
|
||||
};
|
||||
}
|
||||
|
||||
private assertMember(chatId: string, callerId: string): void {
|
||||
private async assertMember(chatId: string, callerId: string): Promise<void> {
|
||||
if (!isUuid(chatId)) {
|
||||
throw new ApiError('invalid_request', 'chatId must be a valid UUID');
|
||||
}
|
||||
if (
|
||||
!this.store.getChatById(chatId) ||
|
||||
!this.store.isMember(chatId, callerId)
|
||||
) {
|
||||
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(),
|
||||
};
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user