mirror of
https://github.com/hexastack/hexabot
synced 2025-06-26 18:27:28 +00:00
Merge pull request #791 from yassine-sallemi/701-issue---label-bulk-delete-v2
fix: add label bulk delete
This commit is contained in:
@@ -6,7 +6,7 @@
|
||||
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
|
||||
*/
|
||||
|
||||
import { NotFoundException } from '@nestjs/common';
|
||||
import { BadRequestException, NotFoundException } from '@nestjs/common';
|
||||
import { EventEmitter2 } from '@nestjs/event-emitter';
|
||||
import { MongooseModule } from '@nestjs/mongoose';
|
||||
import { Test } from '@nestjs/testing';
|
||||
@@ -22,6 +22,7 @@ import { RoleModel } from '@/user/schemas/role.schema';
|
||||
import { UserModel } from '@/user/schemas/user.schema';
|
||||
import { RoleService } from '@/user/services/role.service';
|
||||
import { UserService } from '@/user/services/user.service';
|
||||
import { NOT_FOUND_ID } from '@/utils/constants/mock';
|
||||
import { IGNORED_TEST_FIELDS } from '@/utils/test/constants';
|
||||
import { getUpdateOneError } from '@/utils/test/errors/messages';
|
||||
import { labelFixtures } from '@/utils/test/fixtures/label';
|
||||
@@ -48,6 +49,7 @@ describe('LabelController', () => {
|
||||
let labelService: LabelService;
|
||||
let label: Label;
|
||||
let labelToDelete: Label;
|
||||
let secondLabelToDelete: Label;
|
||||
let subscriberService: SubscriberService;
|
||||
|
||||
beforeAll(async () => {
|
||||
@@ -87,6 +89,9 @@ describe('LabelController', () => {
|
||||
labelToDelete = (await labelService.findOne({
|
||||
name: 'TEST_TITLE_2',
|
||||
})) as Label;
|
||||
secondLabelToDelete = (await labelService.findOne({
|
||||
name: 'TEST_TITLE_3',
|
||||
})) as Label;
|
||||
});
|
||||
|
||||
afterEach(jest.clearAllMocks);
|
||||
@@ -230,4 +235,32 @@ describe('LabelController', () => {
|
||||
).rejects.toThrow(getUpdateOneError(Label.name, labelToDelete.id));
|
||||
});
|
||||
});
|
||||
|
||||
describe('deleteMany', () => {
|
||||
it('should delete multiple labels', async () => {
|
||||
const valuesToDelete = [label.id, secondLabelToDelete.id];
|
||||
|
||||
const result = await labelController.deleteMany(valuesToDelete);
|
||||
|
||||
expect(result.deletedCount).toEqual(valuesToDelete.length);
|
||||
const remainingValues = await labelService.find({
|
||||
_id: { $in: valuesToDelete },
|
||||
});
|
||||
expect(remainingValues.length).toBe(0);
|
||||
});
|
||||
|
||||
it('should throw BadRequestException when no IDs are provided', async () => {
|
||||
await expect(labelController.deleteMany([])).rejects.toThrow(
|
||||
BadRequestException,
|
||||
);
|
||||
});
|
||||
|
||||
it('should throw NotFoundException when provided IDs do not exist', async () => {
|
||||
const nonExistentIds = [NOT_FOUND_ID, NOT_FOUND_ID.replace(/9/g, '8')];
|
||||
|
||||
await expect(labelController.deleteMany(nonExistentIds)).rejects.toThrow(
|
||||
NotFoundException,
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
*/
|
||||
|
||||
import {
|
||||
BadRequestException,
|
||||
Body,
|
||||
Controller,
|
||||
Delete,
|
||||
@@ -24,6 +25,7 @@ import { CsrfCheck } from '@tekuconcept/nestjs-csrf';
|
||||
import { CsrfInterceptor } from '@/interceptors/csrf.interceptor';
|
||||
import { LoggerService } from '@/logger/logger.service';
|
||||
import { BaseController } from '@/utils/generics/base-controller';
|
||||
import { DeleteResult } from '@/utils/generics/base-repository';
|
||||
import { PageQueryDto } from '@/utils/pagination/pagination-query.dto';
|
||||
import { PageQueryPipe } from '@/utils/pagination/pagination-query.pipe';
|
||||
import { PopulatePipe } from '@/utils/pipes/populate.pipe';
|
||||
@@ -125,4 +127,29 @@ export class LabelController extends BaseController<
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes multiple Labels by their IDs.
|
||||
* @param ids - IDs of Labels to be deleted.
|
||||
* @returns A Promise that resolves to the deletion result.
|
||||
*/
|
||||
@CsrfCheck(true)
|
||||
@Delete('')
|
||||
@HttpCode(204)
|
||||
async deleteMany(@Body('ids') ids: string[]): Promise<DeleteResult> {
|
||||
if (!ids || ids.length === 0) {
|
||||
throw new BadRequestException('No IDs provided for deletion.');
|
||||
}
|
||||
const deleteResult = await this.labelService.deleteMany({
|
||||
_id: { $in: ids },
|
||||
});
|
||||
|
||||
if (deleteResult.deletedCount === 0) {
|
||||
this.logger.warn(`Unable to delete Labels with provided IDs: ${ids}`);
|
||||
throw new NotFoundException('Labels with provided IDs not found');
|
||||
}
|
||||
|
||||
this.logger.log(`Successfully deleted Labels with IDs: ${ids}`);
|
||||
return deleteResult;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -82,9 +82,13 @@ export class LabelRepository extends BaseRepository<
|
||||
>,
|
||||
_criteria: TFilterQuery<Label>,
|
||||
): Promise<void> {
|
||||
const labels = await this.find(
|
||||
typeof _criteria === 'string' ? { _id: _criteria } : _criteria,
|
||||
);
|
||||
const ids = Array.isArray(_criteria._id?.$in)
|
||||
? _criteria._id.$in
|
||||
: Array.isArray(_criteria._id)
|
||||
? _criteria._id
|
||||
: [_criteria._id];
|
||||
|
||||
const labels = await this.find({ _id: { $in: ids } });
|
||||
this.eventEmitter.emit('hook:label:delete', labels);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
*/
|
||||
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { OnEvent } from '@nestjs/event-emitter';
|
||||
|
||||
import { AttachmentService } from '@/attachment/services/attachment.service';
|
||||
import EventWrapper from '@/channel/lib/EventWrapper';
|
||||
@@ -25,6 +26,7 @@ import { getRandom } from '@/utils/helpers/safeRandom';
|
||||
import { BlockDto } from '../dto/block.dto';
|
||||
import { BlockRepository } from '../repositories/block.repository';
|
||||
import { Block, BlockFull, BlockPopulate } from '../schemas/block.schema';
|
||||
import { Label } from '../schemas/label.schema';
|
||||
import { Context } from '../schemas/types/context';
|
||||
import {
|
||||
BlockMessage,
|
||||
@@ -604,4 +606,32 @@ export class BlockService extends BaseService<
|
||||
}
|
||||
throw new Error('Invalid message format.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates the `trigger_labels` and `assign_labels` fields of a block when a label is deleted.
|
||||
*
|
||||
*
|
||||
* This method removes the deleted label from the `trigger_labels` and `assign_labels` fields of all blocks that have the label.
|
||||
*
|
||||
* @param label The label that is being deleted.
|
||||
*/
|
||||
@OnEvent('hook:label:delete')
|
||||
async handleLabelDelete(labels: Label[]) {
|
||||
const blocks = await this.find({
|
||||
$or: [
|
||||
{ trigger_labels: { $in: labels.map((l) => l.id) } },
|
||||
{ assign_labels: { $in: labels.map((l) => l.id) } },
|
||||
],
|
||||
});
|
||||
|
||||
for (const block of blocks) {
|
||||
const trigger_labels = block.trigger_labels.filter(
|
||||
(labelId) => !labels.find((l) => l.id === labelId),
|
||||
);
|
||||
const assign_labels = block.assign_labels.filter(
|
||||
(labelId) => !labels.find((l) => l.id === labelId),
|
||||
);
|
||||
await this.updateOne(block.id, { trigger_labels, assign_labels });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -30,6 +30,7 @@ import { WebsocketGateway } from '@/websocket/websocket.gateway';
|
||||
|
||||
import { SubscriberDto, SubscriberUpdateDto } from '../dto/subscriber.dto';
|
||||
import { SubscriberRepository } from '../repositories/subscriber.repository';
|
||||
import { Label } from '../schemas/label.schema';
|
||||
import {
|
||||
Subscriber,
|
||||
SubscriberFull,
|
||||
@@ -208,4 +209,24 @@ export class SubscriberService extends BaseService<
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates the `labels` field of a subscriber when a label is deleted.
|
||||
*
|
||||
* This method removes the deleted label from the `labels` field of all subscribers that have the label.
|
||||
*
|
||||
* @param label The label that is being deleted.
|
||||
*/
|
||||
@OnEvent('hook:label:delete')
|
||||
async handleLabelDelete(labels: Label[]) {
|
||||
const subscribers = await this.find({
|
||||
labels: { $in: labels.map((l) => l.id) },
|
||||
});
|
||||
for (const subscriber of subscribers) {
|
||||
const updatedLabels = subscriber.labels.filter(
|
||||
(label) => !labels.find((l) => l.id === label),
|
||||
);
|
||||
await this.updateOne(subscriber.id, { labels: updatedLabels });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
11
api/src/utils/test/fixtures/label.ts
vendored
11
api/src/utils/test/fixtures/label.ts
vendored
@@ -43,6 +43,17 @@ export const labels: TLabelFixtures['values'][] = [
|
||||
name: 'TEST_TITLE_2',
|
||||
title: 'test title 2',
|
||||
},
|
||||
{
|
||||
description: 'test description 3',
|
||||
label_id: {
|
||||
messenger: 'messenger',
|
||||
web: 'web',
|
||||
twitter: 'twitter',
|
||||
dimelo: 'dimelo',
|
||||
},
|
||||
name: 'TEST_TITLE_3',
|
||||
title: 'test title 3',
|
||||
},
|
||||
];
|
||||
|
||||
export const labelFixtures = getFixturesWithDefaultValues<
|
||||
|
||||
Reference in New Issue
Block a user