forked from mtusi2026/mtusi2026lab2
feat: add database and orm
This commit is contained in:
@@ -1,12 +1,14 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ChatsModule } from './chats/chats.module';
|
||||
import { CommonModule } from './common/common.module';
|
||||
import { DbModule } from './db/db.module';
|
||||
import { HealthModule } from './health/health.module';
|
||||
import { MessagesModule } from './messages/messages.module';
|
||||
import { UsersModule } from './users/users.module';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
DbModule,
|
||||
CommonModule,
|
||||
HealthModule,
|
||||
UsersModule,
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -1,25 +1,26 @@
|
||||
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
|
||||
import { validate as isUuid } from '../uuid';
|
||||
import { FastifyRequest } from 'fastify';
|
||||
import { PrismaService } from '../../db/prisma.service';
|
||||
import { toUser } from '../../users/users.service';
|
||||
import { ApiError } from '../filters/api-error';
|
||||
import { StoreService } from '../store/store.service';
|
||||
import { validate as isUuid } from '../uuid';
|
||||
|
||||
@Injectable()
|
||||
export class AuthGuard implements CanActivate {
|
||||
constructor(private readonly store: StoreService) {}
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
canActivate(context: ExecutionContext): boolean {
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const request = context.switchToHttp().getRequest<FastifyRequest>();
|
||||
const header = request.headers['x-user-id'];
|
||||
const userId = Array.isArray(header) ? header[0] : header;
|
||||
if (!userId || !isUuid(userId)) {
|
||||
throw new ApiError('unauthorized', 'Missing or invalid X-User-Id');
|
||||
}
|
||||
const user = this.store.getUserById(userId);
|
||||
if (!user) {
|
||||
const row = await this.prisma.user.findUnique({ where: { id: userId } });
|
||||
if (!row) {
|
||||
throw new ApiError('unauthorized', 'Missing or invalid X-User-Id');
|
||||
}
|
||||
request.currentUser = user;
|
||||
request.currentUser = toUser(row);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { createParamDecorator, ExecutionContext } from '@nestjs/common';
|
||||
import { FastifyRequest } from 'fastify';
|
||||
import { User } from '../store/domain';
|
||||
import { User } from '../domain';
|
||||
|
||||
declare module 'fastify' {
|
||||
interface FastifyRequest {
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
import { Global, Module } from '@nestjs/common';
|
||||
import { AuthGuard } from './auth/auth.guard';
|
||||
import { StoreService } from './store/store.service';
|
||||
|
||||
@Global()
|
||||
@Module({
|
||||
providers: [StoreService, AuthGuard],
|
||||
exports: [StoreService, AuthGuard],
|
||||
providers: [AuthGuard],
|
||||
exports: [AuthGuard],
|
||||
})
|
||||
export class CommonModule {}
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
import { validate as isUuid } from './uuid';
|
||||
|
||||
export interface ChatCursor {
|
||||
id: string;
|
||||
}
|
||||
|
||||
export interface MessageCursor {
|
||||
chatId: string;
|
||||
id: string;
|
||||
}
|
||||
|
||||
export function encodeChatCursor(cursor: ChatCursor): string {
|
||||
return encode(cursor);
|
||||
}
|
||||
|
||||
export function decodeChatCursor(raw: string): ChatCursor | null {
|
||||
const decoded = decode(raw);
|
||||
return decoded && isUuidField(decoded.id) ? { id: decoded.id } : null;
|
||||
}
|
||||
|
||||
export function encodeMessageCursor(cursor: MessageCursor): string {
|
||||
return encode(cursor);
|
||||
}
|
||||
|
||||
export function decodeMessageCursor(raw: string): MessageCursor | null {
|
||||
const decoded = decode(raw);
|
||||
return decoded && isUuidField(decoded.chatId) && isUuidField(decoded.id)
|
||||
? { chatId: decoded.chatId, id: decoded.id }
|
||||
: null;
|
||||
}
|
||||
|
||||
function isUuidField(value: unknown): value is string {
|
||||
return typeof value === 'string' && isUuid(value);
|
||||
}
|
||||
|
||||
function encode(value: object): string {
|
||||
return Buffer.from(JSON.stringify(value), 'utf8').toString('base64url');
|
||||
}
|
||||
|
||||
function decode(raw: string): Record<string, unknown> | null {
|
||||
try {
|
||||
const parsed = JSON.parse(
|
||||
Buffer.from(raw, 'base64url').toString('utf8'),
|
||||
);
|
||||
return typeof parsed === 'object' && parsed !== null ? parsed : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
Logger,
|
||||
} from '@nestjs/common';
|
||||
import { FastifyReply, FastifyRequest } from 'fastify';
|
||||
import { isDatabaseUnavailable } from '../../db/prisma.service';
|
||||
import { ApiError, ErrorCode } from './api-error';
|
||||
|
||||
const CODE_BY_STATUS: Partial<Record<number, ErrorCode>> = {
|
||||
@@ -75,6 +76,13 @@ export class HttpExceptionFilter implements ExceptionFilter {
|
||||
message,
|
||||
};
|
||||
}
|
||||
if (isDatabaseUnavailable(exception)) {
|
||||
return {
|
||||
status: 503,
|
||||
code: 'unavailable',
|
||||
message: 'database unavailable',
|
||||
};
|
||||
}
|
||||
return {
|
||||
status: 500,
|
||||
code: 'internal_error',
|
||||
|
||||
@@ -1,240 +0,0 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { randomUUID } from 'crypto';
|
||||
import { Chat, Message, User } from './domain';
|
||||
|
||||
export interface ChatCursor {
|
||||
id: string;
|
||||
}
|
||||
|
||||
export interface MessageCursor {
|
||||
chatId: string;
|
||||
id: string;
|
||||
}
|
||||
|
||||
interface Ordered {
|
||||
id: string;
|
||||
seq: number;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
type StoredChat = Chat & Ordered;
|
||||
type StoredMessage = Message & Ordered;
|
||||
|
||||
class OrderedList<T extends Ordered> {
|
||||
private readonly items: T[] = [];
|
||||
private readonly indexById = new Map<string, number>();
|
||||
|
||||
push(item: T): void {
|
||||
this.items.push(item);
|
||||
let index = this.items.length - 1;
|
||||
while (
|
||||
index > 0 &&
|
||||
this.items[index - 1].createdAt === item.createdAt &&
|
||||
this.items[index - 1].id > item.id
|
||||
) {
|
||||
this.items[index] = this.items[index - 1];
|
||||
this.indexById.set(this.items[index].id, index);
|
||||
index--;
|
||||
}
|
||||
this.items[index] = item;
|
||||
this.indexById.set(item.id, index);
|
||||
}
|
||||
|
||||
get length(): number {
|
||||
return this.items.length;
|
||||
}
|
||||
|
||||
toArray(): T[] {
|
||||
return this.items;
|
||||
}
|
||||
|
||||
page(afterId: string | null, limit: number): T[] {
|
||||
if (afterId === null) {
|
||||
return this.items.slice(0, limit);
|
||||
}
|
||||
const cursorIndex = this.indexById.get(afterId);
|
||||
const startIndex =
|
||||
cursorIndex === undefined ? this.items.length : cursorIndex + 1;
|
||||
return this.items.slice(startIndex, startIndex + limit);
|
||||
}
|
||||
|
||||
hasMoreAfter(lastId: string): boolean {
|
||||
const cursorIndex = this.indexById.get(lastId);
|
||||
return cursorIndex !== undefined && cursorIndex < this.items.length - 1;
|
||||
}
|
||||
|
||||
hasId(id: string): boolean {
|
||||
return this.indexById.has(id);
|
||||
}
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class StoreService {
|
||||
private readonly usersById = new Map<string, User>();
|
||||
private readonly userIdByUsername = new Map<string, string>();
|
||||
private readonly chatsById = new Map<string, StoredChat>();
|
||||
private readonly chatsByMember = new Map<string, OrderedList<StoredChat>>();
|
||||
private readonly messagesByChatId = new Map<
|
||||
string,
|
||||
OrderedList<StoredMessage>
|
||||
>();
|
||||
private nextChatSeq = 0;
|
||||
private nextMessageSeq = 0;
|
||||
|
||||
createUser(username: string, displayName: string): User | null {
|
||||
if (this.userIdByUsername.has(username)) {
|
||||
return null;
|
||||
}
|
||||
const user: User = {
|
||||
id: randomUUID(),
|
||||
username,
|
||||
displayName,
|
||||
createdAt: new Date().toISOString(),
|
||||
};
|
||||
this.usersById.set(user.id, user);
|
||||
this.userIdByUsername.set(username, user.id);
|
||||
return user;
|
||||
}
|
||||
|
||||
getUserById(id: string): User | undefined {
|
||||
return this.usersById.get(id);
|
||||
}
|
||||
|
||||
createChat(title: string, memberIds: string[]): Chat {
|
||||
const stored: StoredChat = {
|
||||
id: randomUUID(),
|
||||
title,
|
||||
memberIds: [...memberIds],
|
||||
createdAt: new Date().toISOString(),
|
||||
seq: this.nextChatSeq++,
|
||||
};
|
||||
this.chatsById.set(stored.id, stored);
|
||||
for (const memberId of memberIds) {
|
||||
this.chatListFor(memberId).push(stored);
|
||||
}
|
||||
this.messagesByChatId.set(stored.id, new OrderedList<StoredMessage>());
|
||||
return toPublicChat(stored);
|
||||
}
|
||||
|
||||
getChatById(id: string): Chat | undefined {
|
||||
const stored = this.chatsById.get(id);
|
||||
return stored ? toPublicChat(stored) : undefined;
|
||||
}
|
||||
|
||||
isMember(chatId: string, userId: string): boolean {
|
||||
return !!this.chatsById.get(chatId)?.memberIds.includes(userId);
|
||||
}
|
||||
|
||||
listChatsForMember(
|
||||
userId: string,
|
||||
afterCursor: ChatCursor | null,
|
||||
limit: number,
|
||||
): Chat[] {
|
||||
return this.chatListFor(userId)
|
||||
.page(afterCursor?.id ?? null, limit)
|
||||
.map(toPublicChat);
|
||||
}
|
||||
|
||||
hasMoreChatsAfter(userId: string, lastId: string): boolean {
|
||||
return this.chatListFor(userId).hasMoreAfter(lastId);
|
||||
}
|
||||
|
||||
chatCursorExists(userId: string, cursorId: string): boolean {
|
||||
return this.chatListFor(userId).hasId(cursorId);
|
||||
}
|
||||
|
||||
createMessage(chatId: string, senderId: string, text: string): Message {
|
||||
const list = this.messagesByChatId.get(chatId);
|
||||
if (!list) {
|
||||
throw new Error('chat must exist before appending a message');
|
||||
}
|
||||
const stored: StoredMessage = {
|
||||
id: randomUUID(),
|
||||
chatId,
|
||||
senderId,
|
||||
text,
|
||||
createdAt: new Date().toISOString(),
|
||||
seq: this.nextMessageSeq++,
|
||||
};
|
||||
list.push(stored);
|
||||
return toPublicMessage(stored);
|
||||
}
|
||||
|
||||
listMessages(
|
||||
chatId: string,
|
||||
afterCursor: MessageCursor | null,
|
||||
limit: number,
|
||||
): Message[] {
|
||||
const list = this.messagesByChatId.get(chatId);
|
||||
if (!list) {
|
||||
return [];
|
||||
}
|
||||
return list.page(afterCursor?.id ?? null, limit).map(toPublicMessage);
|
||||
}
|
||||
|
||||
hasMoreMessagesAfter(chatId: string, lastId: string): boolean {
|
||||
return this.messagesByChatId.get(chatId)?.hasMoreAfter(lastId) ?? false;
|
||||
}
|
||||
|
||||
messageCursorExists(chatId: string, cursorId: string): boolean {
|
||||
return this.messagesByChatId.get(chatId)?.hasId(cursorId) ?? false;
|
||||
}
|
||||
|
||||
private chatListFor(memberId: string): OrderedList<StoredChat> {
|
||||
let list = this.chatsByMember.get(memberId);
|
||||
if (!list) {
|
||||
list = new OrderedList<StoredChat>();
|
||||
this.chatsByMember.set(memberId, list);
|
||||
}
|
||||
return list;
|
||||
}
|
||||
}
|
||||
|
||||
function toPublicChat(stored: StoredChat): Chat {
|
||||
const { seq: _seq, ...chat } = stored;
|
||||
return chat;
|
||||
}
|
||||
|
||||
function toPublicMessage(stored: StoredMessage): Message {
|
||||
const { seq: _seq, ...message } = stored;
|
||||
return message;
|
||||
}
|
||||
|
||||
export function encodeChatCursor(cursor: ChatCursor): string {
|
||||
return encode(cursor);
|
||||
}
|
||||
|
||||
export function decodeChatCursor(raw: string): ChatCursor | null {
|
||||
const decoded = decode(raw);
|
||||
return decoded && typeof decoded.id === 'string'
|
||||
? { id: decoded.id }
|
||||
: null;
|
||||
}
|
||||
|
||||
export function encodeMessageCursor(cursor: MessageCursor): string {
|
||||
return encode(cursor);
|
||||
}
|
||||
|
||||
export function decodeMessageCursor(raw: string): MessageCursor | null {
|
||||
const decoded = decode(raw);
|
||||
return decoded &&
|
||||
typeof decoded.chatId === 'string' &&
|
||||
typeof decoded.id === 'string'
|
||||
? { chatId: decoded.chatId, id: decoded.id }
|
||||
: null;
|
||||
}
|
||||
|
||||
function encode(value: object): string {
|
||||
return Buffer.from(JSON.stringify(value), 'utf8').toString('base64url');
|
||||
}
|
||||
|
||||
function decode(raw: string): Record<string, unknown> | null {
|
||||
try {
|
||||
const parsed = JSON.parse(
|
||||
Buffer.from(raw, 'base64url').toString('utf8'),
|
||||
);
|
||||
return typeof parsed === 'object' && parsed !== null ? parsed : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { Global, Module } from '@nestjs/common';
|
||||
import { PrismaService } from './prisma.service';
|
||||
|
||||
@Global()
|
||||
@Module({
|
||||
providers: [PrismaService],
|
||||
exports: [PrismaService],
|
||||
})
|
||||
export class DbModule {}
|
||||
@@ -0,0 +1,49 @@
|
||||
import { Injectable, OnModuleDestroy } from '@nestjs/common';
|
||||
import { Prisma, PrismaClient } from '@prisma/client';
|
||||
import { readFileSync } from 'fs';
|
||||
|
||||
const UNAVAILABLE_CODES = new Set(['P1001', 'P1002', 'P1008', 'P1017', 'P2024']);
|
||||
|
||||
@Injectable()
|
||||
export class PrismaService extends PrismaClient implements OnModuleDestroy {
|
||||
constructor() {
|
||||
super({ datasourceUrl: readDatabaseUrl() });
|
||||
}
|
||||
|
||||
async onModuleDestroy(): Promise<void> {
|
||||
await this.$disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
function readDatabaseUrl(): string {
|
||||
const file = process.env.DATABASE_URL_FILE;
|
||||
const url = file ? readFileSync(file, 'utf8').trim() : process.env.DATABASE_URL;
|
||||
if (!url) {
|
||||
throw new Error('DATABASE_URL_FILE or DATABASE_URL must be set');
|
||||
}
|
||||
return url;
|
||||
}
|
||||
|
||||
export function isUniqueViolation(error: unknown): boolean {
|
||||
return (
|
||||
error instanceof Prisma.PrismaClientKnownRequestError &&
|
||||
error.code === 'P2002'
|
||||
);
|
||||
}
|
||||
|
||||
export function isForeignKeyViolation(error: unknown): boolean {
|
||||
return (
|
||||
error instanceof Prisma.PrismaClientKnownRequestError &&
|
||||
error.code === 'P2003'
|
||||
);
|
||||
}
|
||||
|
||||
export function isDatabaseUnavailable(error: unknown): boolean {
|
||||
if (error instanceof Prisma.PrismaClientInitializationError) {
|
||||
return true;
|
||||
}
|
||||
return (
|
||||
error instanceof Prisma.PrismaClientKnownRequestError &&
|
||||
UNAVAILABLE_CODES.has(error.code)
|
||||
);
|
||||
}
|
||||
@@ -1,14 +1,23 @@
|
||||
import { Controller, Get } from '@nestjs/common';
|
||||
import { ApiError } from '../common/filters/api-error';
|
||||
import { PrismaService } from '../db/prisma.service';
|
||||
|
||||
@Controller('health')
|
||||
export class HealthController {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
@Get('live')
|
||||
live(): { status: 'ok' } {
|
||||
return { status: 'ok' };
|
||||
}
|
||||
|
||||
@Get('ready')
|
||||
ready(): { status: 'ok' } {
|
||||
async ready(): Promise<{ status: 'ok' }> {
|
||||
try {
|
||||
await this.prisma.$queryRaw`SELECT 1`;
|
||||
} catch {
|
||||
throw new ApiError('unavailable', 'database unavailable');
|
||||
}
|
||||
return { status: 'ok' };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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(),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { User } from '../../common/store/domain';
|
||||
import { User } from '../../common/domain';
|
||||
|
||||
export interface UserResponse {
|
||||
id: string;
|
||||
|
||||
@@ -8,7 +8,7 @@ import {
|
||||
} from '@nestjs/common';
|
||||
import { AuthGuard } from '../common/auth/auth.guard';
|
||||
import { CurrentUser } from '../common/auth/current-user.decorator';
|
||||
import { User } from '../common/store/domain';
|
||||
import { User } from '../common/domain';
|
||||
import { CreateUserDto } from './dto/create-user.dto';
|
||||
import { toUserResponse, UserResponse } from './dto/user.response';
|
||||
import { UsersService } from './users.service';
|
||||
@@ -19,8 +19,8 @@ export class UsersController {
|
||||
|
||||
@Post()
|
||||
@HttpCode(201)
|
||||
create(@Body() dto: CreateUserDto): UserResponse {
|
||||
const user = this.users.register(dto.username, dto.display_name);
|
||||
async create(@Body() dto: CreateUserDto): Promise<UserResponse> {
|
||||
const user = await this.users.register(dto.username, dto.display_name);
|
||||
return toUserResponse(user);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,17 +1,42 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { ApiError } from '../common/filters/api-error';
|
||||
import { User } from '../common/store/domain';
|
||||
import { StoreService } from '../common/store/store.service';
|
||||
import { User } from '../common/domain';
|
||||
import { PrismaService, isUniqueViolation } from '../db/prisma.service';
|
||||
|
||||
@Injectable()
|
||||
export class UsersService {
|
||||
constructor(private readonly store: StoreService) {}
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
register(username: string, displayName: string): User {
|
||||
const user = this.store.createUser(username, displayName.trim());
|
||||
if (!user) {
|
||||
throw new ApiError('conflict', 'username is already taken');
|
||||
async register(username: string, displayName: string): Promise<User> {
|
||||
try {
|
||||
const row = await this.prisma.user.create({
|
||||
data: { username, displayName: displayName.trim() },
|
||||
});
|
||||
return toUser(row);
|
||||
} catch (error) {
|
||||
if (isUniqueViolation(error)) {
|
||||
throw new ApiError('conflict', 'username is already taken');
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
return user;
|
||||
}
|
||||
|
||||
async findById(id: string): Promise<User | null> {
|
||||
const row = await this.prisma.user.findUnique({ where: { id } });
|
||||
return row ? toUser(row) : null;
|
||||
}
|
||||
}
|
||||
|
||||
export function toUser(row: {
|
||||
id: string;
|
||||
username: string;
|
||||
displayName: string;
|
||||
createdAt: Date;
|
||||
}): User {
|
||||
return {
|
||||
id: row.id,
|
||||
username: row.username,
|
||||
displayName: row.displayName,
|
||||
createdAt: row.createdAt.toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user