forked from mtusi2026/mtusi2026lab4
feat: add attachment download and message attachment links
This commit is contained in:
@@ -1,5 +1,32 @@
|
||||
import { ArrayMaxSize, IsArray, IsString, ValidateIf } from 'class-validator';
|
||||
import {
|
||||
ArrayMaxSize,
|
||||
IsArray,
|
||||
IsString,
|
||||
Validate,
|
||||
ValidateIf,
|
||||
ValidatorConstraint,
|
||||
ValidatorConstraintInterface,
|
||||
} from 'class-validator';
|
||||
import { CodePointLength } from '../../common/dto/code-point-length.validator';
|
||||
import { validate as isUuid } from '../../common/uuid';
|
||||
|
||||
@ValidatorConstraint({ name: 'uniqueUuidList' })
|
||||
class UniqueUuidList implements ValidatorConstraintInterface {
|
||||
validate(value: unknown): boolean {
|
||||
if (
|
||||
!Array.isArray(value) ||
|
||||
!value.every((id) => typeof id === 'string' && isUuid(id))
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
const normalized = (value as string[]).map((id) => id.toLowerCase());
|
||||
return new Set(normalized).size === normalized.length;
|
||||
}
|
||||
|
||||
defaultMessage(): string {
|
||||
return 'attachment_ids must contain unique UUIDs';
|
||||
}
|
||||
}
|
||||
|
||||
export class CreateMessageDto {
|
||||
@IsString()
|
||||
@@ -8,6 +35,7 @@ export class CreateMessageDto {
|
||||
|
||||
@ValidateIf((dto: CreateMessageDto) => dto.attachment_ids !== undefined)
|
||||
@IsArray()
|
||||
@ArrayMaxSize(0, { message: 'attachment_ids must be empty: attachments are not supported' })
|
||||
attachment_ids?: unknown[];
|
||||
@ArrayMaxSize(10)
|
||||
@Validate(UniqueUuidList)
|
||||
attachment_ids?: string[];
|
||||
}
|
||||
|
||||
@@ -21,6 +21,6 @@ export function toMessageResponse(message: Message): MessageResponse {
|
||||
sender_id: message.senderId,
|
||||
text: message.text,
|
||||
created_at: message.createdAt,
|
||||
attachment_ids: [],
|
||||
attachment_ids: message.attachmentIds,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -36,7 +36,13 @@ export class MessagesController {
|
||||
@CurrentUser() user: User,
|
||||
): Promise<MessageResponse> {
|
||||
const key = parseIdempotencyKey(keyRaw);
|
||||
const message = await this.messages.create(chatId, user.id, dto.text, key);
|
||||
const message = await this.messages.create(
|
||||
chatId,
|
||||
user.id,
|
||||
dto.text,
|
||||
(dto.attachment_ids ?? []).map((id) => id.toLowerCase()),
|
||||
key,
|
||||
);
|
||||
return toMessageResponse(message);
|
||||
}
|
||||
|
||||
|
||||
@@ -15,8 +15,20 @@ interface MessageRow {
|
||||
senderId: string;
|
||||
text: string;
|
||||
createdAt: Date;
|
||||
attachmentIds: string[];
|
||||
}
|
||||
|
||||
const ATTACHMENT_LINKS = {
|
||||
attachments: {
|
||||
orderBy: { position: 'asc' },
|
||||
select: { attachmentId: true },
|
||||
},
|
||||
} satisfies Prisma.MessageInclude;
|
||||
|
||||
type MessageWithLinks = Prisma.MessageGetPayload<{
|
||||
include: typeof ATTACHMENT_LINKS;
|
||||
}>;
|
||||
|
||||
class KeyAlreadyUsed extends Error {}
|
||||
|
||||
@Injectable()
|
||||
@@ -30,18 +42,20 @@ export class MessagesService {
|
||||
chatId: string,
|
||||
callerId: string,
|
||||
text: string,
|
||||
attachmentIds: string[],
|
||||
key: string,
|
||||
): Promise<Message> {
|
||||
await this.assertMember(chatId, callerId);
|
||||
if (codePointLength(text.trim()) === 0) {
|
||||
if (codePointLength(text.trim()) === 0 && attachmentIds.length === 0) {
|
||||
throw new ApiError(
|
||||
'invalid_request',
|
||||
'text must not be empty or whitespace-only',
|
||||
'text must not be empty or whitespace-only without attachments',
|
||||
);
|
||||
}
|
||||
await this.assertAttachmentsInChat(chatId, attachmentIds);
|
||||
const scope = { userId: callerId, chatId, key };
|
||||
const requestHash = createHash('sha256')
|
||||
.update(JSON.stringify({ text }))
|
||||
.update(JSON.stringify({ text, attachment_ids: attachmentIds }))
|
||||
.digest('hex');
|
||||
try {
|
||||
return await this.prisma.$transaction(async (tx) => {
|
||||
@@ -52,7 +66,18 @@ export class MessagesService {
|
||||
},
|
||||
});
|
||||
const row = await tx.message.create({
|
||||
data: { chatId, senderId: callerId, text },
|
||||
data: {
|
||||
chatId,
|
||||
senderId: callerId,
|
||||
text,
|
||||
attachments: {
|
||||
create: attachmentIds.map((attachmentId, position) => ({
|
||||
attachmentId,
|
||||
position,
|
||||
})),
|
||||
},
|
||||
},
|
||||
include: ATTACHMENT_LINKS,
|
||||
});
|
||||
const { count } = await tx.idempotencyKey.createMany({
|
||||
data: [{ ...scope, requestHash, messageId: row.id }],
|
||||
@@ -61,7 +86,7 @@ export class MessagesService {
|
||||
if (count === 0) {
|
||||
throw new KeyAlreadyUsed();
|
||||
}
|
||||
return toMessage(row);
|
||||
return linkedMessage(row);
|
||||
});
|
||||
} catch (error) {
|
||||
if (!(error instanceof KeyAlreadyUsed)) {
|
||||
@@ -70,7 +95,7 @@ export class MessagesService {
|
||||
}
|
||||
const stored = await this.prisma.idempotencyKey.findUnique({
|
||||
where: { userId_chatId_key: scope },
|
||||
include: { message: true },
|
||||
include: { message: { include: ATTACHMENT_LINKS } },
|
||||
});
|
||||
if (!stored || stored.requestHash !== requestHash) {
|
||||
throw new ApiError(
|
||||
@@ -78,7 +103,7 @@ export class MessagesService {
|
||||
'Idempotency-Key was already used with a different request',
|
||||
);
|
||||
}
|
||||
return toMessage(stored.message);
|
||||
return linkedMessage(stored.message);
|
||||
}
|
||||
|
||||
async list(
|
||||
@@ -109,7 +134,12 @@ export class MessagesService {
|
||||
after = Prisma.sql`AND (created_at, id) > (${anchor.createdAt}::timestamptz, ${anchor.id}::uuid)`;
|
||||
}
|
||||
const rows = await this.prisma.$queryRaw<MessageRow[]>`
|
||||
SELECT id, chat_id AS "chatId", sender_id AS "senderId", text, created_at AS "createdAt"
|
||||
SELECT id, chat_id AS "chatId", sender_id AS "senderId", text, created_at AS "createdAt",
|
||||
ARRAY(
|
||||
SELECT attachment_id::text FROM message_attachments
|
||||
WHERE message_id = messages.id
|
||||
ORDER BY position
|
||||
) AS "attachmentIds"
|
||||
FROM messages
|
||||
WHERE chat_id = ${chatId}::uuid ${after}
|
||||
ORDER BY created_at, id
|
||||
@@ -128,6 +158,28 @@ export class MessagesService {
|
||||
private assertMember(chatId: string, callerId: string): Promise<void> {
|
||||
return assertChatMember(this.prisma, chatId, callerId);
|
||||
}
|
||||
|
||||
private async assertAttachmentsInChat(
|
||||
chatId: string,
|
||||
attachmentIds: string[],
|
||||
): Promise<void> {
|
||||
if (attachmentIds.length === 0) {
|
||||
return;
|
||||
}
|
||||
const found = await this.prisma.attachment.count({
|
||||
where: { id: { in: attachmentIds }, chatId },
|
||||
});
|
||||
if (found !== attachmentIds.length) {
|
||||
throw new ApiError('not_found', 'attachment not found');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function linkedMessage(row: MessageWithLinks): Message {
|
||||
return toMessage({
|
||||
...row,
|
||||
attachmentIds: row.attachments.map((link) => link.attachmentId),
|
||||
});
|
||||
}
|
||||
|
||||
function toMessage(row: MessageRow): Message {
|
||||
@@ -137,5 +189,6 @@ function toMessage(row: MessageRow): Message {
|
||||
senderId: row.senderId,
|
||||
text: row.text,
|
||||
createdAt: row.createdAt.toISOString(),
|
||||
attachmentIds: row.attachmentIds,
|
||||
};
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user