From 54cff5d4ce6e4981792ca49fdd16a7caa2b16b6e Mon Sep 17 00:00:00 2001 From: R-Sourabh Date: Wed, 16 Oct 2024 17:41:43 +0530 Subject: [PATCH] Improved: the logic of fetching facilityCountByGroup service(#324) --- src/services/FacilityService.ts | 62 ++++++++++++++++----------------- 1 file changed, 30 insertions(+), 32 deletions(-) diff --git a/src/services/FacilityService.ts b/src/services/FacilityService.ts index f77085d..d3df474 100644 --- a/src/services/FacilityService.ts +++ b/src/services/FacilityService.ts @@ -554,46 +554,44 @@ const fetchArchivedFacilities = async (): Promise => { const fetchFacilityCountByGroup = async (facilityGroupIds: any): Promise => { if (!facilityGroupIds.length) return [] - let allResponseData = [] as any + let facilityMemberResponses = [] as any; let viewIndex = 0; - - const params = { - inputFields: { - facilityGroupId: facilityGroupIds, // Send all facilityGroupIds at once - facilityGroupId_op: "in" - }, - viewSize: 250, // maximum view size - viewIndex: viewIndex, - entityName: 'FacilityGroupAndMember', - noConditionFind: "Y", - filterByDate: 'Y', - fieldList: ['facilityGroupId', 'facilityId'] - } - + let resp = {} as any; + try { - let responseData; do { - params.viewIndex = viewIndex; - const facilityCountResponse = await api({ + const params = { + inputFields: { + facilityGroupId: facilityGroupIds, // Send all facilityGroupIds at once + facilityGroupId_op: "in" + }, + viewSize: 250, // maximum view size + viewIndex, + entityName: 'FacilityGroupAndMember', + noConditionFind: "Y", + filterByDate: 'Y', + fieldList: ['facilityGroupId', 'facilityId'] + }; + + resp = await api({ url: 'performFind', method: 'POST', data: params - }) - - if (hasError(facilityCountResponse) && !facilityCountResponse?.data?.count) { - logger.error('Failed to fetch facility count for some groups') + }); + + if (!hasError(resp) && resp.data.count) { + facilityMemberResponses = [...facilityMemberResponses, ...resp.data.docs]; + viewIndex++; + } else { + throw resp.data; } - - responseData = facilityCountResponse?.data?.docs - allResponseData = allResponseData.concat(responseData) - viewIndex++ - } while (responseData.length >= 250) - - return allResponseData.reduce((facilityCountByGroup: any, responseData: any) => { - if (facilityCountByGroup[responseData.facilityGroupId]) { - facilityCountByGroup[responseData.facilityGroupId] += 1 + } while (resp.data.docs.length >= 250); + + return facilityMemberResponses.reduce((facilityCountByGroup: any, facilityData: any) => { + if (facilityCountByGroup[facilityData.facilityGroupId]) { + facilityCountByGroup[facilityData.facilityGroupId] += 1; } else { - facilityCountByGroup[responseData.facilityGroupId] = 1 + facilityCountByGroup[facilityData.facilityGroupId] = 1 } return facilityCountByGroup }, {})