Files
mtusi2026lab2/app/src/messages/messages.service.ts
T
2026-10-10 02:13:35 +03:00

77 lines
2.0 KiB
TypeScript

import { BadRequestException, Injectable } from '@nestjs/common';
import { decodeCursor, encodeCursor } from '../common/http/cursor.js';
import type { Page } from '../common/http/page.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';
import { MessagesCacheService } from './cache/messages-cache.service.js';
@Injectable()
export class MessagesService {
constructor(
private readonly messagesRepository: MessagesRepository,
private readonly chatsService: ChatsService,
private readonly cache: MessagesCacheService,
) {}
async create(
chatId: string,
input: CreateMessageDto,
currentUser: User,
): Promise<Message> {
await this.chatsService.getForUser(chatId, currentUser);
if ([...input.text].every((character) => /\s/u.test(character)))
throw new BadRequestException('Message text cannot be blank');
return this.messagesRepository.create(
chatId,
currentUser.id,
input.text,
);
}
async list(
chatId: string,
currentUser: User,
limit: number,
cursorValue?: string,
): Promise<Page<Message>> {
await this.chatsService.getForUser(chatId, currentUser);
const scope = `messages:${chatId}`;
const cursor = cursorValue
? decodeCursor(cursorValue, scope)
: undefined;
const version = await this.messagesRepository.getVersion(
chatId,
currentUser.id,
);
const page = await this.cache.getOrLoad(
chatId,
version,
cursorValue,
limit,
async () => {
const loaded = await this.messagesRepository.findPage(
chatId,
limit,
cursor,
);
const lastLoaded = loaded.items.at(-1);
return {
items: loaded.items,
next_cursor:
loaded.hasMore && lastLoaded
? encodeCursor({
scope,
created_at: lastLoaded.created_at,
id: lastLoaded.id,
})
: null,
};
},
);
return page as Page<Message>;
}
}