import { BadRequestException, Injectable, NotFoundException, } from '@nestjs/common'; import { randomUUID } from 'node:crypto'; import { decodeCursor, encodeCursor, isAfter, } from '../common/http/cursor.js'; import type { User } from '../users/user.js'; import { UsersService } from '../users/users.service.js'; import type { Chat } from './chat.js'; import type { CreateChatDto } from './dto/create-chat.dto.js'; import { ChatsRepository } from './chats.repository.js'; @Injectable() export class ChatsService { constructor( private readonly chatsRepository: ChatsRepository, private readonly usersService: UsersService, ) {} create(input: CreateChatDto, currentUser: User): Chat { if (!input.member_ids.includes(currentUser.id)) { throw new BadRequestException('Current user must be a chat member'); } for (const memberId of input.member_ids) { if (!this.usersService.findById(memberId)) { throw new BadRequestException('Chat member does not exist'); } } const chat: Chat = { id: randomUUID(), title: input.title, member_ids: [...input.member_ids], created_at: new Date().toISOString(), }; this.chatsRepository.save(chat); return chat; } getForUser(chatId: string, currentUser: User): Chat { const chat = this.chatsRepository.findById(chatId); if (!chat || !chat.member_ids.includes(currentUser.id)) { throw new NotFoundException(); } return chat; } listForUser( currentUser: User, limit: number, cursorValue?: string, ): { items: Chat[]; next_cursor: string | null } { const scope = `chats:${currentUser.id}`; const cursor = cursorValue ? decodeCursor(cursorValue, scope) : undefined; const chats = this.chatsRepository .findAll() .filter((chat) => chat.member_ids.includes(currentUser.id)) .sort((left, right) => { const byDate = left.created_at.localeCompare(right.created_at); return byDate !== 0 ? byDate : left.id.localeCompare(right.id); }); const start = cursor ? chats.findIndex((chat) => isAfter(chat.created_at, chat.id, cursor)) : 0; const visible = chats.slice(start < 0 ? chats.length : start); const items = visible.slice(0, limit); const hasMore = visible.length > limit; const last = items.at(-1); return { items, next_cursor: hasMore && last ? encodeCursor({ scope, created_at: last.created_at, id: last.id, }) : null, }; } }