feat: add database and orm
This commit is contained in:
@@ -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 { ChatsService } from './chats.service';
|
||||
import {
|
||||
ChatPageResponse,
|
||||
@@ -27,31 +27,31 @@ export class ChatsController {
|
||||
|
||||
@Post()
|
||||
@HttpCode(201)
|
||||
create(
|
||||
async create(
|
||||
@Body() dto: CreateChatDto,
|
||||
@CurrentUser() user: User,
|
||||
): ChatResponse {
|
||||
const chat = this.chats.create(dto.title, dto.member_ids, user.id);
|
||||
): Promise<ChatResponse> {
|
||||
const chat = await this.chats.create(dto.title, dto.member_ids, user.id);
|
||||
return toChatResponse(chat);
|
||||
}
|
||||
|
||||
@Get()
|
||||
list(
|
||||
async list(
|
||||
@CurrentUser() user: User,
|
||||
@Query('limit') limitRaw: unknown,
|
||||
@Query('cursor') cursorRaw: unknown,
|
||||
): ChatPageResponse {
|
||||
): Promise<ChatPageResponse> {
|
||||
const limit = parseLimit(limitRaw);
|
||||
const cursor = rawCursorParam(cursorRaw);
|
||||
return this.chats.listForMember(user.id, limit, cursor);
|
||||
}
|
||||
|
||||
@Get(':chatId')
|
||||
getOne(
|
||||
async getOne(
|
||||
@Param('chatId') chatId: string,
|
||||
@CurrentUser() user: User,
|
||||
): ChatResponse {
|
||||
const chat = this.chats.getForMember(chatId, user.id);
|
||||
): Promise<ChatResponse> {
|
||||
const chat = await this.chats.getForMember(chatId, user.id);
|
||||
return toChatResponse(chat);
|
||||
}
|
||||
}
|
||||
|
||||
+86
-29
@@ -1,67 +1,124 @@
|
||||
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 {
|
||||
decodeChatCursor,
|
||||
encodeChatCursor,
|
||||
} from '../common/store/store.service';
|
||||
import { Chat } from '../common/store/domain';
|
||||
import { StoreService } from '../common/store/store.service';
|
||||
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 store: StoreService) {}
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
create(title: string, memberIds: string[], callerId: string): Chat {
|
||||
async create(
|
||||
title: string,
|
||||
memberIds: string[],
|
||||
callerId: string,
|
||||
): Promise<Chat> {
|
||||
if (!memberIds.includes(callerId)) {
|
||||
throw new ApiError(
|
||||
'invalid_request',
|
||||
'member_ids must include the caller',
|
||||
);
|
||||
}
|
||||
for (const id of memberIds) {
|
||||
if (!isUuid(id) || !this.store.getUserById(id)) {
|
||||
const invalid = memberIds.find((id) => !isUuid(id));
|
||||
if (invalid) {
|
||||
throw new ApiError('invalid_request', `unknown member_id: ${invalid}`);
|
||||
}
|
||||
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',
|
||||
`unknown member_id: ${id}`,
|
||||
'member_ids contain an unknown user',
|
||||
);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
return this.store.createChat(title.trim(), memberIds);
|
||||
}
|
||||
|
||||
getForMember(chatId: string, callerId: string): Chat {
|
||||
async getForMember(chatId: string, callerId: string): Promise<Chat> {
|
||||
if (!isUuid(chatId)) {
|
||||
throw new ApiError('invalid_request', 'chatId must be a valid UUID');
|
||||
}
|
||||
const chat = this.store.getChatById(chatId);
|
||||
if (!chat || !chat.memberIds.includes(callerId)) {
|
||||
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 chat;
|
||||
return toChat({
|
||||
...chat,
|
||||
memberIds: chat.members.map((m) => m.userId),
|
||||
});
|
||||
}
|
||||
|
||||
listForMember(
|
||||
async listForMember(
|
||||
callerId: string,
|
||||
limit: number,
|
||||
rawCursor: string | null,
|
||||
): ChatPageResponse {
|
||||
const cursor = rawCursor === null ? null : decodeChatCursor(rawCursor);
|
||||
if (rawCursor !== null && cursor === null) {
|
||||
throw new ApiError('invalid_request', 'invalid cursor');
|
||||
): 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)`;
|
||||
}
|
||||
if (cursor && !this.store.chatCursorExists(callerId, cursor.id)) {
|
||||
throw new ApiError('invalid_request', 'invalid cursor');
|
||||
}
|
||||
const items = this.store.listChatsForMember(callerId, cursor, limit);
|
||||
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];
|
||||
const hasMore = last
|
||||
? this.store.hasMoreChatsAfter(callerId, last.id)
|
||||
: false;
|
||||
return {
|
||||
items: items.map(toChatResponse),
|
||||
next_cursor: hasMore ? encodeChatCursor({ id: last.id }) : null,
|
||||
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(),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Chat } from '../../common/store/domain';
|
||||
import { Chat } from '../../common/domain';
|
||||
|
||||
export interface ChatResponse {
|
||||
id: string;
|
||||
|
||||
Reference in New Issue
Block a user