Skip to content

Commit 17776af

Browse files
committed
Add countAll endpoint to IdentitiesCrudController and service for filtered identity counts
1 parent 3a4a658 commit 17776af

File tree

2 files changed

+50
-13
lines changed

2 files changed

+50
-13
lines changed

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

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import {
1313
import { ApiOperation, ApiParam, ApiTags } from '@nestjs/swagger';
1414
import {
1515
FilterOptions,
16+
filterSchema,
1617
FilterSchema,
1718
SearchFilterOptions,
1819
SearchFilterSchema,
@@ -198,6 +199,29 @@ export class IdentitiesCrudController extends AbstractController {
198199
});
199200
}
200201

202+
@Post('count-all')
203+
@ApiOperation({ summary: "Compte le nombre d'identitées en fonctions des filtres fournis via un body de counts" })
204+
public async countAll(
205+
@Res() res: Response,
206+
@Body() body: {
207+
[key: string]: FilterSchema;
208+
},
209+
@SearchFilterOptions() searchFilterOptions: FilterOptions,
210+
): Promise<Response<number>> {
211+
const filters = {}
212+
for (const key in body) {
213+
filters[key] = filterSchema(body[key]);
214+
console.log('filters', key, body[key], filters[key]);
215+
}
216+
217+
const totals = await this._service.countAll(filters, searchFilterOptions);
218+
219+
return res.status(HttpStatus.OK).json({
220+
statusCode: HttpStatus.OK,
221+
data: totals,
222+
});
223+
}
224+
201225
@Patch(':_id([0-9a-fA-F]{24})')
202226
@ApiParam({ name: '_id', type: String })
203227
@ApiUpdateDecorator(IdentitiesUpdateDto, IdentitiesDto)

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

Lines changed: 26 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
11
import { AbstractIdentitiesService } from '~/management/identities/abstract-identities.service';
22
import { AbstractSchema } from '~/_common/abstracts/schemas/abstract.schema';
3-
import { Document, ModifyResult, Query, QueryOptions, SaveOptions, Types, UpdateQuery } from 'mongoose';
3+
import { Document, FilterQuery, ModifyResult, MongooseBaseQueryOptions, Query, QueryOptions, SaveOptions, Types, UpdateQuery } from 'mongoose';
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';
77
import { HttpException } from '@nestjs/common';
8-
import { omit } from 'radash';
8+
import { map, omit } from 'radash';
9+
import { CountOptions } from 'mongodb';
910

1011
export class IdentitiesCrudService extends AbstractIdentitiesService {
1112
public async create<T extends AbstractSchema | Document>(
@@ -14,18 +15,18 @@ export class IdentitiesCrudService extends AbstractIdentitiesService {
1415
): Promise<Document<T, any, T>> {
1516
data = this.transformNullsToString(data);
1617
await this.checkInetOrgPersonJpegPhoto(data);
17-
if(await this.checkMailAndUid(data) === false){
18+
if (await this.checkMailAndUid(data) === false) {
1819
this.logger.error('Uid ou mail déjà présent dans une autre identité');
1920
throw new HttpException("Uid ou mail déjà présent dans une autre identité", 400);
2021
}
2122
const logPrefix = `Validation [${data.inetOrgPerson.cn}]:`;
2223
this.logger.log(`${logPrefix} Starting inetOrgPerson validation.`);
23-
const check={
24-
objectClasses: ['inetorgperson'],
25-
attributes:{ 'inetorgperson':data.inetOrgPerson}
24+
const check = {
25+
objectClasses: ['inetorgperson'],
26+
attributes: { 'inetorgperson': data.inetOrgPerson }
2627
}
2728
//pour la validation le employeeNumber doit exister on en met un avec une valeur par defaut
28-
check.attributes.inetorgperson.employeeNumber=["1"];
29+
check.attributes.inetorgperson.employeeNumber = ["1"];
2930
let validations = await this._validation.validate(check);
3031
const created: Document<T, any, T> = await super.create(data, options);
3132
return created;
@@ -42,17 +43,17 @@ export class IdentitiesCrudService extends AbstractIdentitiesService {
4243
const logPrefix = `Validation [${update.inetOrgPerson.cn}]:`;
4344
try {
4445
this.logger.log(`${logPrefix} Starting additionalFields transformation.`);
45-
if(update.hasOwnProperty('metadata')){
46+
if (update.hasOwnProperty('metadata')) {
4647
//suppresion de la clé metadata
47-
delete(update.metadata);
48+
delete (update.metadata);
4849
}
4950

5051
await this._validation.transform(update.additionalFields);
5152

5253
this.logger.log(`${logPrefix} Starting inetOrgPerson validation.`);
53-
const check={
54+
const check = {
5455
objectClasses: ['inetorgperson'],
55-
attributes:{ 'inetorgperson':update.inetOrgPerson}
56+
attributes: { 'inetorgperson': update.inetOrgPerson }
5657
}
5758
let validationsInetOrg = await this._validation.validate(check);
5859
let validationsAdFields = await this._validation.validate(update.additionalFields);
@@ -76,7 +77,7 @@ export class IdentitiesCrudService extends AbstractIdentitiesService {
7677
}
7778
}
7879
// check mail and Uid
79-
if(await this.checkMailAndUid(update) === false){
80+
if (await this.checkMailAndUid(update) === false) {
8081
this.logger.error('Uid ou mail déjà présent dans une autre identité');
8182
throw new HttpException("Uid ou mail déjà présent dans une autre identité", 400);
8283
}
@@ -135,5 +136,17 @@ export class IdentitiesCrudService extends AbstractIdentitiesService {
135136
return deleted;
136137
}
137138

138-
139+
public async countAll<T extends AbstractSchema | Document>(filters: {
140+
[key: string]: FilterQuery<T>;
141+
}, 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+
}
149+
}
150+
return res;
151+
}
139152
}

0 commit comments

Comments
 (0)