forked from mtusi2026/mtusi2026lab2
chore: migrate minimum from lab1
This commit is contained in:
@@ -0,0 +1,17 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ChatsModule } from './chats/chats.module';
|
||||
import { CommonModule } from './common/common.module';
|
||||
import { HealthModule } from './health/health.module';
|
||||
import { MessagesModule } from './messages/messages.module';
|
||||
import { UsersModule } from './users/users.module';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
CommonModule,
|
||||
HealthModule,
|
||||
UsersModule,
|
||||
ChatsModule,
|
||||
MessagesModule,
|
||||
],
|
||||
})
|
||||
export class AppModule {}
|
||||
@@ -0,0 +1,57 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Get,
|
||||
HttpCode,
|
||||
Param,
|
||||
Post,
|
||||
Query,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
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 { ChatsService } from './chats.service';
|
||||
import {
|
||||
ChatPageResponse,
|
||||
ChatResponse,
|
||||
toChatResponse,
|
||||
} from './dto/chat.response';
|
||||
import { CreateChatDto } from './dto/create-chat.dto';
|
||||
|
||||
@Controller('api/v1/chats')
|
||||
@UseGuards(AuthGuard)
|
||||
export class ChatsController {
|
||||
constructor(private readonly chats: ChatsService) {}
|
||||
|
||||
@Post()
|
||||
@HttpCode(201)
|
||||
create(
|
||||
@Body() dto: CreateChatDto,
|
||||
@CurrentUser() user: User,
|
||||
): ChatResponse {
|
||||
const chat = this.chats.create(dto.title, dto.member_ids, user.id);
|
||||
return toChatResponse(chat);
|
||||
}
|
||||
|
||||
@Get()
|
||||
list(
|
||||
@CurrentUser() user: User,
|
||||
@Query('limit') limitRaw: unknown,
|
||||
@Query('cursor') cursorRaw: unknown,
|
||||
): ChatPageResponse {
|
||||
const limit = parseLimit(limitRaw);
|
||||
const cursor = rawCursorParam(cursorRaw);
|
||||
return this.chats.listForMember(user.id, limit, cursor);
|
||||
}
|
||||
|
||||
@Get(':chatId')
|
||||
getOne(
|
||||
@Param('chatId') chatId: string,
|
||||
@CurrentUser() user: User,
|
||||
): ChatResponse {
|
||||
const chat = this.chats.getForMember(chatId, user.id);
|
||||
return toChatResponse(chat);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { CommonModule } from '../common/common.module';
|
||||
import { ChatsController } from './chats.controller';
|
||||
import { ChatsService } from './chats.service';
|
||||
|
||||
@Module({
|
||||
imports: [CommonModule],
|
||||
controllers: [ChatsController],
|
||||
providers: [ChatsService],
|
||||
exports: [ChatsService],
|
||||
})
|
||||
export class ChatsModule {}
|
||||
@@ -0,0 +1,67 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
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 { ChatPageResponse, toChatResponse } from './dto/chat.response';
|
||||
|
||||
@Injectable()
|
||||
export class ChatsService {
|
||||
constructor(private readonly store: StoreService) {}
|
||||
|
||||
create(title: string, memberIds: string[], callerId: string): 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)) {
|
||||
throw new ApiError(
|
||||
'invalid_request',
|
||||
`unknown member_id: ${id}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
return this.store.createChat(title.trim(), memberIds);
|
||||
}
|
||||
|
||||
getForMember(chatId: string, callerId: string): 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)) {
|
||||
throw new ApiError('not_found', 'chat not found');
|
||||
}
|
||||
return chat;
|
||||
}
|
||||
|
||||
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');
|
||||
}
|
||||
if (cursor && !this.store.chatCursorExists(callerId, cursor.id)) {
|
||||
throw new ApiError('invalid_request', 'invalid cursor');
|
||||
}
|
||||
const items = this.store.listChatsForMember(callerId, cursor, limit);
|
||||
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,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import { Chat } from '../../common/store/domain';
|
||||
|
||||
export interface ChatResponse {
|
||||
id: string;
|
||||
title: string;
|
||||
member_ids: string[];
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface ChatPageResponse {
|
||||
items: ChatResponse[];
|
||||
next_cursor: string | null;
|
||||
}
|
||||
|
||||
export function toChatResponse(chat: Chat): ChatResponse {
|
||||
return {
|
||||
id: chat.id,
|
||||
title: chat.title,
|
||||
member_ids: chat.memberIds,
|
||||
created_at: chat.createdAt,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { ArrayMinSize, ArrayUnique, IsArray, IsString } from 'class-validator';
|
||||
import { CodePointLength } from '../../common/dto/code-point-length.validator';
|
||||
import { NotBlank } from '../../common/dto/not-blank.validator';
|
||||
|
||||
export class CreateChatDto {
|
||||
@NotBlank()
|
||||
@CodePointLength(1, 100)
|
||||
title!: string;
|
||||
|
||||
@IsArray()
|
||||
@ArrayMinSize(1)
|
||||
@ArrayUnique()
|
||||
@IsString({ each: true })
|
||||
member_ids!: string[];
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
|
||||
import { validate as isUuid } from '../uuid';
|
||||
import { FastifyRequest } from 'fastify';
|
||||
import { ApiError } from '../filters/api-error';
|
||||
import { StoreService } from '../store/store.service';
|
||||
|
||||
@Injectable()
|
||||
export class AuthGuard implements CanActivate {
|
||||
constructor(private readonly store: StoreService) {}
|
||||
|
||||
canActivate(context: ExecutionContext): 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) {
|
||||
throw new ApiError('unauthorized', 'Missing or invalid X-User-Id');
|
||||
}
|
||||
request.currentUser = user;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { createParamDecorator, ExecutionContext } from '@nestjs/common';
|
||||
import { FastifyRequest } from 'fastify';
|
||||
import { User } from '../store/domain';
|
||||
|
||||
declare module 'fastify' {
|
||||
interface FastifyRequest {
|
||||
currentUser?: User;
|
||||
}
|
||||
}
|
||||
|
||||
export const CurrentUser = createParamDecorator(
|
||||
(_data: unknown, ctx: ExecutionContext): User => {
|
||||
const request = ctx.switchToHttp().getRequest<FastifyRequest>();
|
||||
if (!request.currentUser) {
|
||||
throw new Error('CurrentUser used without AuthGuard');
|
||||
}
|
||||
return request.currentUser;
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,10 @@
|
||||
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],
|
||||
})
|
||||
export class CommonModule {}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { registerDecorator, ValidationOptions } from 'class-validator';
|
||||
|
||||
export function codePointLength(value: string): number {
|
||||
return [...value].length;
|
||||
}
|
||||
|
||||
export function CodePointLength(
|
||||
min: number,
|
||||
max: number,
|
||||
options?: ValidationOptions,
|
||||
) {
|
||||
return function (object: object, propertyName: string) {
|
||||
registerDecorator({
|
||||
name: 'codePointLength',
|
||||
target: object.constructor,
|
||||
propertyName,
|
||||
constraints: [min, max],
|
||||
options,
|
||||
validator: {
|
||||
validate(value: unknown): boolean {
|
||||
if (typeof value !== 'string') {
|
||||
return false;
|
||||
}
|
||||
const length = codePointLength(value);
|
||||
return length >= min && length <= max;
|
||||
},
|
||||
defaultMessage(): string {
|
||||
return `${propertyName} must be between ${min} and ${max} Unicode code points`;
|
||||
},
|
||||
},
|
||||
});
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { registerDecorator, ValidationOptions } from 'class-validator';
|
||||
|
||||
export function NotBlank(options?: ValidationOptions) {
|
||||
return function (object: object, propertyName: string) {
|
||||
registerDecorator({
|
||||
name: 'notBlank',
|
||||
target: object.constructor,
|
||||
propertyName,
|
||||
options,
|
||||
validator: {
|
||||
validate(value: unknown): boolean {
|
||||
return typeof value === 'string' && value.trim().length > 0;
|
||||
},
|
||||
defaultMessage(): string {
|
||||
return `${propertyName} must not be empty or whitespace-only`;
|
||||
},
|
||||
},
|
||||
});
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import { ApiError } from '../filters/api-error';
|
||||
|
||||
const DEFAULT_LIMIT = 50;
|
||||
const MIN_LIMIT = 1;
|
||||
const MAX_LIMIT = 100;
|
||||
|
||||
export function parseLimit(raw: unknown): number {
|
||||
if (raw === undefined) {
|
||||
return DEFAULT_LIMIT;
|
||||
}
|
||||
const value = Array.isArray(raw) ? raw[0] : raw;
|
||||
if (typeof value !== 'string' || !/^\d+$/.test(value)) {
|
||||
throw new ApiError('invalid_request', 'limit must be an integer');
|
||||
}
|
||||
const limit = Number(value);
|
||||
if (limit < MIN_LIMIT || limit > MAX_LIMIT) {
|
||||
throw new ApiError(
|
||||
'invalid_request',
|
||||
`limit must be between ${MIN_LIMIT} and ${MAX_LIMIT}`,
|
||||
);
|
||||
}
|
||||
return limit;
|
||||
}
|
||||
|
||||
export function rawCursorParam(raw: unknown): string | null {
|
||||
if (raw === undefined) {
|
||||
return null;
|
||||
}
|
||||
const value = Array.isArray(raw) ? raw[0] : raw;
|
||||
if (typeof value !== 'string' || value.length === 0) {
|
||||
throw new ApiError(
|
||||
'invalid_request',
|
||||
'cursor must be a non-empty string',
|
||||
);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { HttpException, HttpStatus } from '@nestjs/common';
|
||||
|
||||
export type ErrorCode =
|
||||
| 'invalid_request'
|
||||
| 'unauthorized'
|
||||
| 'not_found'
|
||||
| 'conflict'
|
||||
| 'payload_too_large'
|
||||
| 'unsupported_media_type'
|
||||
| 'rate_limited'
|
||||
| 'unavailable'
|
||||
| 'internal_error';
|
||||
|
||||
const STATUS_BY_CODE: Record<ErrorCode, number> = {
|
||||
invalid_request: HttpStatus.BAD_REQUEST,
|
||||
unauthorized: HttpStatus.UNAUTHORIZED,
|
||||
not_found: HttpStatus.NOT_FOUND,
|
||||
conflict: HttpStatus.CONFLICT,
|
||||
payload_too_large: HttpStatus.PAYLOAD_TOO_LARGE,
|
||||
unsupported_media_type: HttpStatus.UNSUPPORTED_MEDIA_TYPE,
|
||||
rate_limited: HttpStatus.TOO_MANY_REQUESTS,
|
||||
unavailable: HttpStatus.SERVICE_UNAVAILABLE,
|
||||
internal_error: HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
};
|
||||
|
||||
export class ApiError extends HttpException {
|
||||
constructor(
|
||||
public readonly code: ErrorCode,
|
||||
message: string,
|
||||
) {
|
||||
super(message, STATUS_BY_CODE[code]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
import {
|
||||
ArgumentsHost,
|
||||
Catch,
|
||||
ExceptionFilter,
|
||||
HttpException,
|
||||
HttpStatus,
|
||||
Logger,
|
||||
} from '@nestjs/common';
|
||||
import { FastifyReply, FastifyRequest } from 'fastify';
|
||||
import { ApiError, ErrorCode } from './api-error';
|
||||
|
||||
const CODE_BY_STATUS: Partial<Record<number, ErrorCode>> = {
|
||||
[HttpStatus.BAD_REQUEST]: 'invalid_request',
|
||||
[HttpStatus.UNAUTHORIZED]: 'unauthorized',
|
||||
[HttpStatus.NOT_FOUND]: 'not_found',
|
||||
[HttpStatus.CONFLICT]: 'conflict',
|
||||
[HttpStatus.PAYLOAD_TOO_LARGE]: 'payload_too_large',
|
||||
[HttpStatus.UNSUPPORTED_MEDIA_TYPE]: 'unsupported_media_type',
|
||||
[HttpStatus.TOO_MANY_REQUESTS]: 'rate_limited',
|
||||
[HttpStatus.SERVICE_UNAVAILABLE]: 'unavailable',
|
||||
};
|
||||
|
||||
interface Resolved {
|
||||
status: number;
|
||||
code: ErrorCode;
|
||||
message: string;
|
||||
}
|
||||
|
||||
@Catch()
|
||||
export class HttpExceptionFilter implements ExceptionFilter {
|
||||
private readonly logger = new Logger('HttpExceptionFilter');
|
||||
|
||||
catch(exception: unknown, host: ArgumentsHost): void {
|
||||
const ctx = host.switchToHttp();
|
||||
const reply = ctx.getResponse<FastifyReply>();
|
||||
const request = ctx.getRequest<FastifyRequest>();
|
||||
const requestId = request.requestId;
|
||||
|
||||
const { status, code, message } = this.resolve(exception);
|
||||
if (status >= 500) {
|
||||
this.logger.error(
|
||||
`${request.method} ${request.url} -> ${status}: ${message}`,
|
||||
);
|
||||
}
|
||||
|
||||
reply
|
||||
.code(status)
|
||||
.header('x-request-id', requestId)
|
||||
.send({ error: { code, message, request_id: requestId } });
|
||||
}
|
||||
|
||||
private resolve(exception: unknown): Resolved {
|
||||
if (exception instanceof ApiError) {
|
||||
return {
|
||||
status: exception.getStatus(),
|
||||
code: exception.code,
|
||||
message: exception.message,
|
||||
};
|
||||
}
|
||||
if (exception instanceof HttpException) {
|
||||
const status = exception.getStatus();
|
||||
const code = CODE_BY_STATUS[status] ?? 'internal_error';
|
||||
const message =
|
||||
extractMessage(exception.getResponse()) ?? exception.message;
|
||||
return { status, code, message };
|
||||
}
|
||||
const fastifyStatus = (exception as { statusCode?: unknown })
|
||||
?.statusCode;
|
||||
if (typeof fastifyStatus === 'number' && CODE_BY_STATUS[fastifyStatus]) {
|
||||
const message =
|
||||
exception instanceof Error ? exception.message : 'Invalid request';
|
||||
return {
|
||||
status: fastifyStatus,
|
||||
code: CODE_BY_STATUS[fastifyStatus]!,
|
||||
message,
|
||||
};
|
||||
}
|
||||
return {
|
||||
status: 500,
|
||||
code: 'internal_error',
|
||||
message: 'Internal server error',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function extractMessage(response: unknown): string | null {
|
||||
if (typeof response === 'string') {
|
||||
return response;
|
||||
}
|
||||
if (
|
||||
typeof response === 'object' &&
|
||||
response !== null &&
|
||||
'message' in response
|
||||
) {
|
||||
const value = (response as { message: unknown }).message;
|
||||
if (typeof value === 'string') {
|
||||
return value;
|
||||
}
|
||||
if (Array.isArray(value) && value.every((v) => typeof v === 'string')) {
|
||||
return value.join('; ');
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { randomUUID } from 'crypto';
|
||||
import { FastifyInstance, FastifyRequest } from 'fastify';
|
||||
|
||||
const REQUEST_ID_HEADER = 'x-request-id';
|
||||
|
||||
declare module 'fastify' {
|
||||
interface FastifyRequest {
|
||||
requestId: string;
|
||||
}
|
||||
}
|
||||
|
||||
export function registerRequestId(instance: FastifyInstance): void {
|
||||
instance.addHook('onRequest', (request: FastifyRequest, reply, done) => {
|
||||
request.requestId = randomUUID();
|
||||
reply.header(REQUEST_ID_HEADER, request.requestId);
|
||||
done();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
export interface User {
|
||||
id: string;
|
||||
username: string;
|
||||
displayName: string;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
export interface Chat {
|
||||
id: string;
|
||||
title: string;
|
||||
memberIds: string[];
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
export interface Message {
|
||||
id: string;
|
||||
chatId: string;
|
||||
senderId: string;
|
||||
text: string;
|
||||
createdAt: string;
|
||||
}
|
||||
@@ -0,0 +1,240 @@
|
||||
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,6 @@
|
||||
const UUID_PATTERN =
|
||||
/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
||||
|
||||
export function validate(value: string): boolean {
|
||||
return UUID_PATTERN.test(value);
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { ValidationPipe } from '@nestjs/common';
|
||||
import { NestFastifyApplication } from '@nestjs/platform-fastify';
|
||||
import { HttpExceptionFilter } from './common/filters/http-exception.filter';
|
||||
import { registerRequestId } from './common/interceptors/request-id';
|
||||
|
||||
export function configureApp(app: NestFastifyApplication): void {
|
||||
registerRequestId(app.getHttpAdapter().getInstance());
|
||||
|
||||
app.useGlobalPipes(
|
||||
new ValidationPipe({
|
||||
whitelist: true,
|
||||
forbidNonWhitelisted: true,
|
||||
transform: true,
|
||||
forbidUnknownValues: true,
|
||||
}),
|
||||
);
|
||||
app.useGlobalFilters(new HttpExceptionFilter());
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { Controller, Get } from '@nestjs/common';
|
||||
|
||||
@Controller('health')
|
||||
export class HealthController {
|
||||
@Get('live')
|
||||
live(): { status: 'ok' } {
|
||||
return { status: 'ok' };
|
||||
}
|
||||
|
||||
@Get('ready')
|
||||
ready(): { status: 'ok' } {
|
||||
return { status: 'ok' };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { HealthController } from './health.controller';
|
||||
|
||||
@Module({
|
||||
controllers: [HealthController],
|
||||
})
|
||||
export class HealthModule {}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
import { Logger } from '@nestjs/common';
|
||||
import { NestFactory } from '@nestjs/core';
|
||||
import {
|
||||
FastifyAdapter,
|
||||
NestFastifyApplication,
|
||||
} from '@nestjs/platform-fastify';
|
||||
import { AppModule } from './app.module';
|
||||
import { configureApp } from './configure-app';
|
||||
|
||||
async function bootstrap(): Promise<void> {
|
||||
const app = await NestFactory.create<NestFastifyApplication>(
|
||||
AppModule,
|
||||
new FastifyAdapter(),
|
||||
{
|
||||
bufferLogs: true,
|
||||
},
|
||||
);
|
||||
|
||||
configureApp(app);
|
||||
app.enableShutdownHooks();
|
||||
|
||||
const host = process.env.APP_HOST ?? '0.0.0.0';
|
||||
const port = Number(process.env.APP_PORT ?? 8080);
|
||||
await app.listen(port, host);
|
||||
Logger.log(`Listening on http://${host}:${port}`, 'Bootstrap');
|
||||
}
|
||||
|
||||
bootstrap().catch((error) => {
|
||||
Logger.error('Fatal error during bootstrap', error);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -0,0 +1,8 @@
|
||||
import { IsString } from 'class-validator';
|
||||
import { CodePointLength } from '../../common/dto/code-point-length.validator';
|
||||
|
||||
export class CreateMessageDto {
|
||||
@IsString()
|
||||
@CodePointLength(0, 4000)
|
||||
text!: string;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { Message } from '../../common/store/domain';
|
||||
|
||||
export interface MessageResponse {
|
||||
id: string;
|
||||
chat_id: string;
|
||||
sender_id: string;
|
||||
text: string;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface MessagePageResponse {
|
||||
items: MessageResponse[];
|
||||
next_cursor: string | null;
|
||||
}
|
||||
|
||||
export function toMessageResponse(message: Message): MessageResponse {
|
||||
return {
|
||||
id: message.id,
|
||||
chat_id: message.chatId,
|
||||
sender_id: message.senderId,
|
||||
text: message.text,
|
||||
created_at: message.createdAt,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Get,
|
||||
HttpCode,
|
||||
Param,
|
||||
Post,
|
||||
Query,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
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 { CreateMessageDto } from './dto/create-message.dto';
|
||||
import {
|
||||
MessagePageResponse,
|
||||
MessageResponse,
|
||||
toMessageResponse,
|
||||
} from './dto/message.response';
|
||||
import { MessagesService } from './messages.service';
|
||||
|
||||
@Controller('api/v1/chats/:chatId/messages')
|
||||
@UseGuards(AuthGuard)
|
||||
export class MessagesController {
|
||||
constructor(private readonly messages: MessagesService) {}
|
||||
|
||||
@Post()
|
||||
@HttpCode(201)
|
||||
create(
|
||||
@Param('chatId') chatId: string,
|
||||
@Body() dto: CreateMessageDto,
|
||||
@CurrentUser() user: User,
|
||||
): MessageResponse {
|
||||
const message = this.messages.create(chatId, user.id, dto.text);
|
||||
return toMessageResponse(message);
|
||||
}
|
||||
|
||||
@Get()
|
||||
list(
|
||||
@Param('chatId') chatId: string,
|
||||
@CurrentUser() user: User,
|
||||
@Query('limit') limitRaw: unknown,
|
||||
@Query('cursor') cursorRaw: unknown,
|
||||
): MessagePageResponse {
|
||||
const limit = parseLimit(limitRaw);
|
||||
const cursor = rawCursorParam(cursorRaw);
|
||||
return this.messages.list(chatId, user.id, limit, cursor);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { CommonModule } from '../common/common.module';
|
||||
import { MessagesController } from './messages.controller';
|
||||
import { MessagesService } from './messages.service';
|
||||
|
||||
@Module({
|
||||
imports: [CommonModule],
|
||||
controllers: [MessagesController],
|
||||
providers: [MessagesService],
|
||||
})
|
||||
export class MessagesModule {}
|
||||
@@ -0,0 +1,73 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { ApiError } from '../common/filters/api-error';
|
||||
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 { validate as isUuid } from '../common/uuid';
|
||||
import { MessagePageResponse, toMessageResponse } from './dto/message.response';
|
||||
|
||||
@Injectable()
|
||||
export class MessagesService {
|
||||
constructor(private readonly store: StoreService) {}
|
||||
|
||||
create(chatId: string, callerId: string, text: string): Message {
|
||||
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);
|
||||
}
|
||||
|
||||
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');
|
||||
}
|
||||
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 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,
|
||||
};
|
||||
}
|
||||
|
||||
private assertMember(chatId: string, callerId: string): 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)
|
||||
) {
|
||||
throw new ApiError('not_found', 'chat not found');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { Matches } from 'class-validator';
|
||||
import { CodePointLength } from '../../common/dto/code-point-length.validator';
|
||||
import { NotBlank } from '../../common/dto/not-blank.validator';
|
||||
|
||||
export class CreateUserDto {
|
||||
@Matches(/^[a-z0-9_]{3,32}$/, {
|
||||
message: 'username must match [a-z0-9_]{3,32}',
|
||||
})
|
||||
username!: string;
|
||||
|
||||
@NotBlank()
|
||||
@CodePointLength(1, 100)
|
||||
display_name!: string;
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { User } from '../../common/store/domain';
|
||||
|
||||
export interface UserResponse {
|
||||
id: string;
|
||||
username: string;
|
||||
display_name: string;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export function toUserResponse(user: User): UserResponse {
|
||||
return {
|
||||
id: user.id,
|
||||
username: user.username,
|
||||
display_name: user.displayName,
|
||||
created_at: user.createdAt,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Get,
|
||||
HttpCode,
|
||||
Post,
|
||||
UseGuards,
|
||||
} 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 { CreateUserDto } from './dto/create-user.dto';
|
||||
import { toUserResponse, UserResponse } from './dto/user.response';
|
||||
import { UsersService } from './users.service';
|
||||
|
||||
@Controller('api/v1/users')
|
||||
export class UsersController {
|
||||
constructor(private readonly users: UsersService) {}
|
||||
|
||||
@Post()
|
||||
@HttpCode(201)
|
||||
create(@Body() dto: CreateUserDto): UserResponse {
|
||||
const user = this.users.register(dto.username, dto.display_name);
|
||||
return toUserResponse(user);
|
||||
}
|
||||
|
||||
@Get('me')
|
||||
@UseGuards(AuthGuard)
|
||||
me(@CurrentUser() user: User): UserResponse {
|
||||
return toUserResponse(user);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { CommonModule } from '../common/common.module';
|
||||
import { UsersController } from './users.controller';
|
||||
import { UsersService } from './users.service';
|
||||
|
||||
@Module({
|
||||
imports: [CommonModule],
|
||||
controllers: [UsersController],
|
||||
providers: [UsersService],
|
||||
exports: [UsersService],
|
||||
})
|
||||
export class UsersModule {}
|
||||
@@ -0,0 +1,17 @@
|
||||
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';
|
||||
|
||||
@Injectable()
|
||||
export class UsersService {
|
||||
constructor(private readonly store: StoreService) {}
|
||||
|
||||
register(username: string, displayName: string): User {
|
||||
const user = this.store.createUser(username, displayName.trim());
|
||||
if (!user) {
|
||||
throw new ApiError('conflict', 'username is already taken');
|
||||
}
|
||||
return user;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user