Skip to content

Commit 1f9fe02

Browse files
committed
Refactor countAll method in IdentitiesCrudService to limit filter count and improve performance
1 parent 17776af commit 1f9fe02

File tree

1 file changed

+10
-10
lines changed

1 file changed

+10
-10
lines changed

src/management/identities/identities-crud.service.ts

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,7 @@ import { Document, FilterQuery, ModifyResult, MongooseBaseQueryOptions, Query, Q
44
import { ValidationConfigException, ValidationSchemaException } from '~/_common/errors/ValidationException';
55
import { IdentityState } from '~/management/identities/_enums/states.enum';
66
import { Identities } from '~/management/identities/_schemas/identities.schema';
7-
import { HttpException } from '@nestjs/common';
8-
import { map, omit } from 'radash';
7+
import { BadRequestException, HttpException } from '@nestjs/common';
98
import { CountOptions } from 'mongodb';
109

1110
export class IdentitiesCrudService extends AbstractIdentitiesService {
@@ -139,14 +138,15 @@ export class IdentitiesCrudService extends AbstractIdentitiesService {
139138
public async countAll<T extends AbstractSchema | Document>(filters: {
140139
[key: string]: FilterQuery<T>;
141140
}, options?: (CountOptions & MongooseBaseQueryOptions<T>) | null) {
142-
const res = {}
143-
const maxItems = 500;
144-
for (const key in filters) {
145-
res[key] = await this._model.countDocuments(filters[key], options);
146-
if (res[key] > maxItems) {
147-
throw new HttpException(`La requête a retourné plus de ${maxItems} résultats.`, 400);
148-
}
141+
if (Object.keys(filters).length >= 5) {
142+
throw new BadRequestException('Too many filters');
149143
}
150-
return res;
144+
145+
const entries = Object.entries(filters);
146+
const results = await Promise.all(entries.map(([key, filter]) =>
147+
this._model.countDocuments(filter, options).then(count => [key, count])
148+
));
149+
150+
return Object.fromEntries(results);
151151
}
152152
}

0 commit comments

Comments
 (0)