chore: migrate minimum from lab1
This commit is contained in:
@@ -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');
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user