feat: undo message attachment reference removal

This commit is contained in:
Mohamed Marrouchi 2025-05-09 16:42:00 +01:00
parent 0db40680dc
commit 4f012594cb

View File

@ -11,14 +11,8 @@ import {
InternalServerErrorException, InternalServerErrorException,
Optional, Optional,
} from '@nestjs/common'; } from '@nestjs/common';
import { OnEvent } from '@nestjs/event-emitter';
import { Document, Query } from 'mongoose';
import { Attachment } from '@/attachment/schemas/attachment.schema';
import { AttachmentService } from '@/attachment/services/attachment.service';
import { DeleteResult } from '@/utils/generics/base-repository';
import { BaseService } from '@/utils/generics/base-service'; import { BaseService } from '@/utils/generics/base-service';
import { TFilterQuery } from '@/utils/types/filter.types';
import { import {
SocketGet, SocketGet,
SocketPost, SocketPost,
@ -45,7 +39,6 @@ export class MessageService extends BaseService<
constructor( constructor(
private readonly messageRepository: MessageRepository, private readonly messageRepository: MessageRepository,
private attachmentService: AttachmentService,
@Optional() gateway?: WebsocketGateway, @Optional() gateway?: WebsocketGateway,
) { ) {
super(messageRepository); super(messageRepository);
@ -134,40 +127,4 @@ export class MessageService extends BaseService<
return lastMessages.reverse(); return lastMessages.reverse();
} }
@OnEvent('hook:attachment:preDelete')
async handleDeleteImage(
_query: Query<
DeleteResult,
Document<Attachment, any, any>,
unknown,
Attachment,
'deleteOne' | 'deleteMany'
>,
criteria: TFilterQuery<Attachment>,
) {
try {
this.logger.log(
'deleting attachment messages containing deleted images',
criteria,
);
const foundAttachments = await this.attachmentService.find(criteria);
for (const attachment of foundAttachments) {
await this.updateMany(
{
'message.attachment.payload.id': attachment.id,
},
{
['message.attachment.payload.id' as any]: null,
},
);
}
} catch (error) {
this.logger.error(
'Unable to cleanup old messages with attachment ids',
error,
);
}
}
} }