feat: init after lab 1

This commit is contained in:
2026-10-01 19:29:22 +03:00
parent 65003b6119
commit f743ee10a2
44 changed files with 8111 additions and 0 deletions
+75
View File
@@ -0,0 +1,75 @@
import {
BadRequestException,
Injectable,
} from '@nestjs/common';
import { randomUUID } from 'node:crypto';
import { decodeCursor, encodeCursor } from '../common/http/cursor.js';
import type { User } from '../users/user.js';
import { ChatsService } from '../chats/chats.service.js';
import type { CreateMessageDto } from './dto/create-message.dto.js';
import type { Message } from './message.js';
import { MessagesRepository } from './messages.repository.js';
@Injectable()
export class MessagesService {
constructor(
private readonly messagesRepository: MessagesRepository,
private readonly chatsService: ChatsService,
) {}
create(
chatId: string,
input: CreateMessageDto,
currentUser: User,
): Message {
const chat = this.chatsService.getForUser(chatId, currentUser);
if ([...input.text].every((character) => /\s/u.test(character))) {
throw new BadRequestException('Message text cannot be blank');
}
const message: Message = {
id: randomUUID(),
chat_id: chat.id,
sender_id: currentUser.id,
text: input.text,
created_at: new Date().toISOString(),
};
this.messagesRepository.save(message);
return message;
}
list(
chatId: string,
currentUser: User,
limit: number,
cursorValue?: string,
): { items: Message[]; next_cursor: string | null } {
this.chatsService.getForUser(chatId, currentUser);
const scope = `messages:${chatId}`;
const cursor = cursorValue
? decodeCursor(cursorValue, scope)
: undefined;
const messages = this.messagesRepository.findByChatId(chatId);
const start = cursor
? this.messagesRepository.findFirstAfter(chatId, cursor)
: 0;
const items = messages.slice(start, start + limit);
const hasMore = messages.length > start + limit;
const last = items.at(-1);
return {
items,
next_cursor:
hasMore && last
? encodeCursor({
scope,
created_at: last.created_at,
id: last.id,
})
: null,
};
}
}