From c4757302cdf463863f62c61a89687f182fd73488 Mon Sep 17 00:00:00 2001 From: ashish-egov <137176738+ashish-egov@users.noreply.github.com> Date: Tue, 18 Jun 2024 13:47:31 +0530 Subject: [PATCH 1/4] Update request.ts --- .../src/server/utils/request.ts | 161 ++++++++++-------- 1 file changed, 90 insertions(+), 71 deletions(-) diff --git a/utilities/project-factory/src/server/utils/request.ts b/utilities/project-factory/src/server/utils/request.ts index ae5ba11dd49..543feaa338c 100644 --- a/utilities/project-factory/src/server/utils/request.ts +++ b/utilities/project-factory/src/server/utils/request.ts @@ -1,6 +1,7 @@ import { Response } from "express"; // Importing necessary module Response from Express import { getFormattedStringForDebug, logger } from "./logger"; // Importing logger from logger module import { cacheResponse, getCachedResponse, throwErrorViaRequest } from "./genericUtils"; // Importing necessary functions from genericUtils module +import config from "../config"; var Axios = require("axios").default; // Importing axios library var get = require("lodash/get"); // Importing get function from lodash library @@ -64,86 +65,104 @@ const httpRequest = async ( _method: string = "post", responseType: string = "", headers: any = defaultheader, - sendStatusCode: any = false + sendStatusCode: any = false, + dontThrowError: any = false, + retry: any = false ): Promise => { - try { - if (headers && headers.cachekey && cacheEnabled) { - const cacheData = getCachedResponse(headers.cachekey); // Get cached response data - if (cacheData) { - return cacheData; // Return cached data if available + let attempt = 0; // Track the number of attempts + const maxAttempts = parseInt(config.values.maxHttpRetries) || 4; // Maximum number of retry attempts + + while (attempt < maxAttempts) { + try { + if (headers && headers.cachekey && cacheEnabled) { + const cacheData = getCachedResponse(headers.cachekey); // Get cached response data + if (cacheData) { + return cacheData; // Return cached data if available + } + logger.info( + "NO CACHE FOUND :: REQUEST :: " + + JSON.stringify(headers.cachekey) + ); } logger.info( - "NO CACHE FOUND :: REQUEST :: " + - JSON.stringify(headers.cachekey) + "INTER-SERVICE :: REQUEST :: " + + getServiceName(_url) + + " CRITERIA :: " + + JSON.stringify(_params) ); - } - logger.info( - "INTER-SERVICE :: REQUEST :: " + - getServiceName(_url) + - " CRITERIA :: " + - JSON.stringify(_params) - ); - logger.debug("INTER-SERVICE :: REQUESTBODY :: " + getFormattedStringForDebug(_requestBody)) - // Make HTTP request using Axios - const response = await Axios({ - method: _method, - url: _url, - data: _requestBody, - params: _params, - headers: { ...defaultheader, ...headers }, - responseType, - }); + logger.debug("INTER-SERVICE :: REQUESTBODY :: " + getFormattedStringForDebug(_requestBody)) + // Make HTTP request using Axios + const response = await axiosInstance({ + method: _method, + url: _url, + data: _requestBody, + params: _params, + headers: { ...defaultheader, ...headers }, + responseType, + }); - const responseStatus = parseInt(get(response, "status"), 10); // Get response status - logger.info( - "INTER-SERVICE :: SUCCESS :: " + - getServiceName(_url) + - ":: CODE :: " + - responseStatus - ); - logger.debug("INTER-SERVICE :: RESPONSEBODY :: " +getFormattedStringForDebug(response.data)); + const responseStatus = parseInt(get(response, "status"), 10); // Get response status + logger.info( + "INTER-SERVICE :: SUCCESS :: " + + getServiceName(_url) + + ":: CODE :: " + + responseStatus + ); + logger.debug("INTER-SERVICE :: RESPONSEBODY :: " + getFormattedStringForDebug(response.data)); - // If response status is successful, cache the response data if caching is enabled - if (responseStatus === 200 || responseStatus === 201 || responseStatus === 202) { - if (headers && headers.cachekey) { - cacheResponse(response.data, headers.cachekey) + // If response status is successful, cache the response data if caching is enabled + if (responseStatus === 200 || responseStatus === 201 || responseStatus === 202) { + if (headers && headers.cachekey) { + cacheResponse(response.data, headers.cachekey); + } + // Return response data with status code if sendStatusCode flag is false + if (!sendStatusCode) + return response.data; + else return { ...response.data, "statusCode": responseStatus }; } - // Return response data with status code if sendStatusCode flag is false - if (!sendStatusCode) - return response.data; - else return { ...response.data, "statusCode": responseStatus } - } - } catch (error: any) { - var errorResponse = error?.response; // Get error response - // Log error details - logger.error( - "INTER-SERVICE :: FAILURE :: " + - getServiceName(_url) + - ":: CODE :: " + - errorResponse?.status + - ":: ERROR :: " + - errorResponse?.data?.Errors?.[0]?.code || error + - ":: DESCRIPTION :: " + - errorResponse?.data?.Errors?.[0]?.description - ); - logger.error("error occured while making request to " + - getServiceName(_url) + - ": error response :" + - (errorResponse ? parseInt(errorResponse?.status, 10) : error?.message)) - logger.error(":: ERROR STACK :: " + error?.stack || error); - // Throw error response via request if error response contains errors - if (errorResponse?.data?.Errors?.[0]) { - errorResponse.data.Errors[0].status = errorResponse?.data?.Errors?.[0]?.status || errorResponse?.status - throwErrorViaRequest(errorResponse?.data?.Errors?.[0]); - } - else { - // Throw error message via request - throwErrorViaRequest( - "error occured while making request to " + + } catch (error: any) { + var errorResponse = error?.response; // Get error response + // Log error details + logger.error( + "INTER-SERVICE :: FAILURE :: " + getServiceName(_url) + - ": error response :" + - (errorResponse ? parseInt(errorResponse?.status, 10) : error?.message) + ":: CODE :: " + + errorResponse?.status + + ":: ERROR :: " + + errorResponse?.data?.Errors?.[0]?.code || error + + ":: DESCRIPTION :: " + + errorResponse?.data?.Errors?.[0]?.description ); + logger.error("error occurred while making request to " + + getServiceName(_url) + + ": error response :" + + (errorResponse ? parseInt(errorResponse?.status, 10) : error?.message)) + logger.error(":: ERROR STACK :: " + error?.stack || error); + if (!dontThrowError) { + // Throw error response via request if error response contains errors + if (errorResponse?.data?.Errors?.[0]) { + errorResponse.data.Errors[0].status = errorResponse?.data?.Errors?.[0]?.status || errorResponse?.status + throwErrorViaRequest(errorResponse?.data?.Errors?.[0]); + } else { + // Throw error message via request + throwErrorViaRequest( + "error occurred while making request to " + + getServiceName(_url) + + ": error response :" + + (errorResponse ? parseInt(errorResponse?.status, 10) : error?.message) + ); + } + } else if (dontThrowError && retry) { + attempt++; // Increment the attempt count + if (attempt >= maxAttempts) { + return errorResponse?.data || { Errors: [{ code: error.message, description: error.stack }] }; // Return the error response or error details + } + // Wait for a short period before retrying + logger.info(`Waiting for 20 seconds before retrying httprequest with url ${_url}`); + await new Promise(resolve => setTimeout(resolve, 20000)); + } else { + return errorResponse?.data || { Errors: [{ code: error.message, description: error.stack }] }; // Return the error response or error details + } } } }; From 8f722bf651d9767b9ab31c94e931085a811bf9af Mon Sep 17 00:00:00 2001 From: ashish-egov Date: Tue, 18 Jun 2024 14:21:22 +0530 Subject: [PATCH 2/4] Feat : updated httprequest --- .../src/server/api/campaignApis.ts | 8 +- .../src/server/api/genericApis.ts | 22 ++- .../src/server/config/index.ts | 1 + .../src/server/utils/request.ts | 47 +++--- .../src/server/validators/genericValidator.ts | 146 +++--------------- 5 files changed, 66 insertions(+), 158 deletions(-) diff --git a/utilities/project-factory/src/server/api/campaignApis.ts b/utilities/project-factory/src/server/api/campaignApis.ts index 407c0bbb837..361bc7da76d 100644 --- a/utilities/project-factory/src/server/api/campaignApis.ts +++ b/utilities/project-factory/src/server/api/campaignApis.ts @@ -282,7 +282,7 @@ const createBatchRequest = async (request: any, batch: any[], mobileNumberRowNum includeDeleted: true }; logger.info("Individual search to validate the mobile no initiated"); - const response = await httpRequest(config.host.healthIndividualHost + config.paths.healthIndividualSearch, searchBody, params); + const response = await httpRequest(config.host.healthIndividualHost + config.paths.healthIndividualSearch, searchBody, params, undefined, undefined, undefined, undefined, true); if (!response) { throwError("COMMON", 400, "INTERNAL_SERVER_ERROR", "Error occurred during user search while validating mobile number."); @@ -465,7 +465,7 @@ async function getEmployeesBasedOnUuids(dataToCreate: any[], request: any) { }; try { - const response = await httpRequest(searchUrl, searchBody, params); + const response = await httpRequest(searchUrl, searchBody, params, undefined, undefined, undefined, undefined, true); if (response && response.Employees) { employeesSearched = employeesSearched.concat(response.Employees); } else { @@ -672,7 +672,7 @@ async function handleUserProcess(request: any, createAndSearchConfig: any, param newRequestBody.Employees = Employees } if (newRequestBody.Employees.length > 0) { - var responsePayload = await httpRequest(createAndSearchConfig?.createBulkDetails?.url, newRequestBody, params, "post", undefined, undefined, true); + var responsePayload = await httpRequest(createAndSearchConfig?.createBulkDetails?.url, newRequestBody, params, "post", undefined, undefined, true, true); if (responsePayload?.Employees && responsePayload?.Employees?.length > 0) { enrichDataToCreateForUser(dataToCreate, responsePayload, request); } @@ -908,7 +908,7 @@ async function confirmProjectParentCreation(request: any, projectId: any) { async function projectCreate(projectCreateBody: any, request: any) { logger.info("Project creation url " + config.host.projectHost + config.paths.projectCreate) logger.debug("Project creation body " + getFormattedStringForDebug(projectCreateBody)) - const projectCreateResponse = await httpRequest(config.host.projectHost + config.paths.projectCreate, projectCreateBody); + const projectCreateResponse = await httpRequest(config.host.projectHost + config.paths.projectCreate, projectCreateBody, undefined, undefined, undefined, undefined, undefined, true); logger.debug("Project creation response" + getFormattedStringForDebug(projectCreateResponse)) if (projectCreateResponse?.Project[0]?.id) { logger.info("Project created successfully with name " + JSON.stringify(projectCreateResponse?.Project[0]?.name)) diff --git a/utilities/project-factory/src/server/api/genericApis.ts b/utilities/project-factory/src/server/api/genericApis.ts index ca145f332a0..e10b9679610 100644 --- a/utilities/project-factory/src/server/api/genericApis.ts +++ b/utilities/project-factory/src/server/api/genericApis.ts @@ -4,7 +4,6 @@ import FormData from "form-data"; // Import FormData for handling multipart/form import { httpRequest } from "../utils/request"; // Import httpRequest function for making HTTP requests import { getFormattedStringForDebug, logger } from "../utils/logger"; // Import logger for logging import { correctParentValues, findMapValue, generateActivityMessage, getBoundaryRelationshipData, getDataSheetReady, getLocalizedHeaders, sortCampaignDetails, throwError } from "../utils/genericUtils"; // Import utility functions -import { validateProjectFacilityResponse, validateProjectResourceResponse, validateStaffResponse } from "../validators/genericValidator"; // Import validation functions import { extractCodesFromBoundaryRelationshipResponse, generateFilteredBoundaryData, getConfigurableColumnHeadersBasedOnCampaignType, getFiltersFromCampaignSearchResponse, getLocalizedName } from '../utils/campaignUtils'; // Import utility functions import { getCampaignSearchResponse, getHierarchy } from './campaignApis'; import { validateMappingId } from '../utils/campaignMappingUtils'; @@ -670,14 +669,17 @@ async function createStaff(resouceBody: any) { undefined, "post", undefined, - undefined + undefined, + undefined, + false, + true ); logger.info("Project Staff mapping created"); logger.debug( "Project Staff mapping response " + getFormattedStringForDebug(staffResponse) ); - validateStaffResponse(staffResponse); + // validateStaffResponse(staffResponse); } /** @@ -696,14 +698,17 @@ async function createProjectResource(resouceBody: any) { undefined, "post", undefined, - undefined + undefined, + undefined, + false, + true ); logger.debug("Project Resource Created"); logger.debug( "Project Resource Creation response :: " + getFormattedStringForDebug(projectResourceResponse) ); - validateProjectResourceResponse(projectResourceResponse); + // validateProjectResourceResponse(projectResourceResponse); } /** @@ -722,14 +727,17 @@ async function createProjectFacility(resouceBody: any) { undefined, "post", undefined, - undefined + undefined, + undefined, + false, + true ); logger.info("Project Facility Created"); logger.debug( "Project Facility Creation response" + getFormattedStringForDebug(projectFacilityResponse) ); - validateProjectFacilityResponse(projectFacilityResponse); + // validateProjectFacilityResponse(projectFacilityResponse); } // Helper function to create staff diff --git a/utilities/project-factory/src/server/config/index.ts b/utilities/project-factory/src/server/config/index.ts index 47ee3d834f6..90739c75c2a 100644 --- a/utilities/project-factory/src/server/config/index.ts +++ b/utilities/project-factory/src/server/config/index.ts @@ -146,6 +146,7 @@ const config = { matchFacilityData: false, retryCount: process.env.CREATE_RESOURCE_RETRY_COUNT || "3", notCreateUserIfAlreadyThere: process.env.NOT_CREATE_USER_IF_ALREADY_THERE || false, + maxHttpRetries: "4" } }; // Exporting getErrorCodes function and config object diff --git a/utilities/project-factory/src/server/utils/request.ts b/utilities/project-factory/src/server/utils/request.ts index 543feaa338c..415ec37f169 100644 --- a/utilities/project-factory/src/server/utils/request.ts +++ b/utilities/project-factory/src/server/utils/request.ts @@ -66,8 +66,8 @@ const httpRequest = async ( responseType: string = "", headers: any = defaultheader, sendStatusCode: any = false, - dontThrowError: any = false, - retry: any = false + retry: any = false, + dontThrowError: any = false ): Promise => { let attempt = 0; // Track the number of attempts const maxAttempts = parseInt(config.values.maxHttpRetries) || 4; // Maximum number of retry attempts @@ -138,33 +138,42 @@ const httpRequest = async ( ": error response :" + (errorResponse ? parseInt(errorResponse?.status, 10) : error?.message)) logger.error(":: ERROR STACK :: " + error?.stack || error); - if (!dontThrowError) { - // Throw error response via request if error response contains errors - if (errorResponse?.data?.Errors?.[0]) { - errorResponse.data.Errors[0].status = errorResponse?.data?.Errors?.[0]?.status || errorResponse?.status - throwErrorViaRequest(errorResponse?.data?.Errors?.[0]); - } else { - // Throw error message via request - throwErrorViaRequest( - "error occurred while making request to " + - getServiceName(_url) + - ": error response :" + - (errorResponse ? parseInt(errorResponse?.status, 10) : error?.message) - ); - } - } else if (dontThrowError && retry) { + if (retry) { attempt++; // Increment the attempt count if (attempt >= maxAttempts) { - return errorResponse?.data || { Errors: [{ code: error.message, description: error.stack }] }; // Return the error response or error details + if (dontThrowError) { + return errorResponse?.data || { Errors: [{ code: error.message, description: error.stack }] }; + } + else { + throwTheHttpError(errorResponse, error, _url); + } } // Wait for a short period before retrying logger.info(`Waiting for 20 seconds before retrying httprequest with url ${_url}`); await new Promise(resolve => setTimeout(resolve, 20000)); + } else if (dontThrowError) { + return errorResponse?.data || { Errors: [{ code: error.message, description: error.stack }] }; } else { - return errorResponse?.data || { Errors: [{ code: error.message, description: error.stack }] }; // Return the error response or error details + throwTheHttpError(errorResponse, error, _url); } } } }; +function throwTheHttpError(errorResponse?: any, error?: any, _url?: string) { + // Throw error response via request if error response contains errors + if (errorResponse?.data?.Errors?.[0]) { + errorResponse.data.Errors[0].status = errorResponse?.data?.Errors?.[0]?.status || errorResponse?.status + throwErrorViaRequest(errorResponse?.data?.Errors?.[0]); + } else { + // Throw error message via request + throwErrorViaRequest( + "error occurred while making request to " + + getServiceName(_url) + + ": error response :" + + (errorResponse ? parseInt(errorResponse?.status, 10) : error?.message) + ); + } +} + export { httpRequest }; // Exporting the httpRequest function for use in other modules diff --git a/utilities/project-factory/src/server/validators/genericValidator.ts b/utilities/project-factory/src/server/validators/genericValidator.ts index bc19d3a369b..426f1de67e7 100644 --- a/utilities/project-factory/src/server/validators/genericValidator.ts +++ b/utilities/project-factory/src/server/validators/genericValidator.ts @@ -79,116 +79,6 @@ function validateBodyViaSchema(schema: any, objectData: any) { } } -// function validateBoundaries(requestBody: any) { -// const { boundaryCode } = requestBody?.Campaign; -// if (!boundaryCode) { -// throwError("COMMON", 400, "VALIDATION_ERROR", "Enter BoundaryCode In Campaign"); -// } -// for (const campaignDetails of requestBody?.Campaign?.CampaignDetails) { -// const { boundaryCode: campaignBoundaryCode, parentBoundaryCode } = campaignDetails; -// if (!parentBoundaryCode && boundaryCode != campaignBoundaryCode) { -// throwError("COMMON", 400, "VALIDATION_ERROR", "Enter ParentBoundaryCode In CampaignDetails"); -// } -// if (!campaignBoundaryCode) { -// throwError("COMMON", 400, "VALIDATION_ERROR", "Enter BoundaryCode In CampaignDetails"); -// } -// } -// } - -// Function to validate the user ID -// async function validateUserId(resourceId: any, requestBody: any) { -// // Constructing the search body for user validation -// const userSearchBody = { -// RequestInfo: requestBody?.RequestInfo, -// tenantId: requestBody?.Campaign?.tenantId.split('.')?.[0], -// uuid: [resourceId] -// } - -// // Logging user search URL and request body -// logger.info("User search url : " + config.host.userHost + config.paths.userSearch); -// logger.info("userSearchBody : " + JSON.stringify(userSearchBody)); - -// // Performing the HTTP request to validate the user ID -// const response = await httpRequest(config.host.userHost + config.paths.userSearch, userSearchBody); - -// // Handling response errors if user ID is invalid -// if (!response?.user?.[0]?.uuid) { -// throwError("COMMON", 400, "VALIDATION_ERROR", "Invalid resourceId for resource type staff with id " + resourceId); -// } -// } - -// Function to validate the product variant ID -// async function validateProductVariantId(resourceId: any, requestBody: any) { -// // Constructing the search body for product variant validation -// const productVariantSearchBody = { -// RequestInfo: requestBody?.RequestInfo, -// ProductVariant: { id: [resourceId] } -// } -// const productVariantSearchParams = { -// limit: 10, -// offset: 0, -// tenantId: requestBody?.Campaign?.tenantId.split('.')?.[0] -// } - -// // Logging product variant search URL and request body -// logger.info("ProductVariant search url : " + config.host.productHost + config.paths.productVariantSearch); -// logger.info("productVariantSearchBody : " + JSON.stringify(productVariantSearchBody)); -// logger.info("productVariantSearchParams : " + JSON.stringify(productVariantSearchParams)); - -// // Performing the HTTP request to validate the product variant ID -// const response = await httpRequest(config.host.productHost + config.paths.productVariantSearch, productVariantSearchBody, productVariantSearchParams); - -// // Handling response errors if product variant ID is invalid -// if (!response?.ProductVariant?.[0]?.id) { -// throwError("COMMON", 400, "VALIDATION_ERROR", "Invalid resourceId for resource type resource with id " + resourceId); -// } -// } - -// Function to validate the project facility ID -// async function validateProjectFacilityId(resourceId: any, requestBody: any) { -// // Constructing the search body for project facility validation -// const facilitySearchBody = { -// RequestInfo: requestBody?.RequestInfo, -// Facility: { -// id: [resourceId] -// } -// } -// const facilitySearchParams = { -// limit: 10, -// offset: 0, -// tenantId: requestBody?.Campaign?.tenantId?.split('.')?.[0] -// } - -// // Logging facility search URL and request body -// logger.info("Facility search url : " + config.host.facilityHost + config.paths.facilitySearch); -// logger.info("facilitySearchBody : " + JSON.stringify(facilitySearchBody)); -// logger.info("facilitySearchParams : " + JSON.stringify(facilitySearchParams)); - -// // Performing the HTTP request to validate the project facility ID -// const response = await httpRequest(config.host.facilityHost + config.paths.facilitySearch, facilitySearchBody, facilitySearchParams); - -// // Handling response errors if project facility ID is invalid -// if (!response?.Facilities?.[0]?.id) { -// throwError("COMMON", 400, "VALIDATION_ERROR", "Invalid resourceId for resource type facility with id " + resourceId); -// } -// } - -// Function to validate the resource ID based on its type -// async function validateResourceId(type: any, resourceId: any, requestBody: any) { -// // Dispatching validation based on resource type -// // if (type == "staff") { -// // await validateUserId(resourceId, requestBody) -// // } -// // else if (type == "resource") { -// // await validateProductVariantId(resourceId, requestBody) -// // } -// // else if (type == "facility") { -// // await validateProjectFacilityId(resourceId, requestBody) -// // } -// // else { -// // throwError("COMMON", 400, "VALIDATION_ERROR", "Invalid resource type " + type); -// // } -// } // Function to validate the resources associated with a campaign async function validateProjectResource(requestBody: any) { for (const campaignDetails of requestBody?.Campaign?.CampaignDetails) { @@ -252,25 +142,25 @@ function validatedProjectResponseAndUpdateId(projectResponse: any, projectBody: } // Function to validate project staff response -function validateStaffResponse(staffResponse: any) { - if (!staffResponse?.ProjectStaff?.id) { - throwError("CAMPAIGN", 500, "RESOURCE_CREATION_ERROR", "Project staff creation failed."); - } -} +// function validateStaffResponse(staffResponse: any) { +// if (!staffResponse?.ProjectStaff?.id) { +// throwError("CAMPAIGN", 500, "RESOURCE_CREATION_ERROR", "Project staff creation failed."); +// } +// } // Function to validate project resource response -function validateProjectResourceResponse(projectResouceResponse: any) { - if (!projectResouceResponse?.ProjectResource?.id) { - throwError("CAMPAIGN", 500, "RESOURCE_CREATION_ERROR", "Project Resource creation failed."); - } -} +// function validateProjectResourceResponse(projectResouceResponse: any) { +// if (!projectResouceResponse?.ProjectResource?.id) { +// throwError("CAMPAIGN", 500, "RESOURCE_CREATION_ERROR", "Project Resource creation failed."); +// } +// } // Function to validate project facility response -function validateProjectFacilityResponse(projectFacilityResponse: any) { - if (!projectFacilityResponse?.ProjectFacility?.id) { - throwError("CAMPAIGN", 500, "RESOURCE_CREATION_ERROR", "Project Facility creation failed."); - } -} +// function validateProjectFacilityResponse(projectFacilityResponse: any) { +// if (!projectFacilityResponse?.ProjectFacility?.id) { +// throwError("CAMPAIGN", 500, "RESOURCE_CREATION_ERROR", "Project Facility creation failed."); +// } +// } // Function to validate the hierarchy type async function validateHierarchyType(request: any, hierarchyType: any, tenantId: any) { @@ -324,9 +214,9 @@ export { validateBodyViaSchema, validateCampaignRequest, validatedProjectResponseAndUpdateId, - validateStaffResponse, - validateProjectFacilityResponse, - validateProjectResourceResponse, + // validateStaffResponse, + // validateProjectFacilityResponse, + // validateProjectResourceResponse, validateGenerateRequest, validateHierarchyType, validateCampaignBodyViaSchema From 3b81e6711f12bff5c78e56e5140e6dd0207fd212 Mon Sep 17 00:00:00 2001 From: ashish-egov Date: Tue, 18 Jun 2024 14:45:53 +0530 Subject: [PATCH 3/4] Feat : warning response added --- utilities/project-factory/src/server/utils/request.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/utilities/project-factory/src/server/utils/request.ts b/utilities/project-factory/src/server/utils/request.ts index 415ec37f169..95706d53024 100644 --- a/utilities/project-factory/src/server/utils/request.ts +++ b/utilities/project-factory/src/server/utils/request.ts @@ -138,10 +138,12 @@ const httpRequest = async ( ": error response :" + (errorResponse ? parseInt(errorResponse?.status, 10) : error?.message)) logger.error(":: ERROR STACK :: " + error?.stack || error); + logger.warn(`Error occurred while making request to ${getServiceName(_url)}: returning error response ${JSON.stringify(errorResponse?.data || { Errors: [{ code: error.message, description: error.stack }] })}`); if (retry) { attempt++; // Increment the attempt count if (attempt >= maxAttempts) { if (dontThrowError) { + logger.warn(`Maximum retry attempts reached for httprequest with url ${_url}`); return errorResponse?.data || { Errors: [{ code: error.message, description: error.stack }] }; } else { @@ -149,9 +151,10 @@ const httpRequest = async ( } } // Wait for a short period before retrying - logger.info(`Waiting for 20 seconds before retrying httprequest with url ${_url}`); + logger.warn(`Waiting for 20 seconds before retrying httprequest with url ${_url}`); await new Promise(resolve => setTimeout(resolve, 20000)); } else if (dontThrowError) { + logger.warn(`Error occurred while making request to ${getServiceName(_url)}: returning error response ${JSON.stringify(errorResponse?.data || { Errors: [{ code: error.message, description: error.stack }] })}`); return errorResponse?.data || { Errors: [{ code: error.message, description: error.stack }] }; } else { throwTheHttpError(errorResponse, error, _url); From e6c76673cd58793724d4644b5fb87b96933841fa Mon Sep 17 00:00:00 2001 From: ashish-egov Date: Tue, 18 Jun 2024 14:46:27 +0530 Subject: [PATCH 4/4] Refactor --- utilities/project-factory/src/server/utils/request.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/utilities/project-factory/src/server/utils/request.ts b/utilities/project-factory/src/server/utils/request.ts index 95706d53024..7e78bf07543 100644 --- a/utilities/project-factory/src/server/utils/request.ts +++ b/utilities/project-factory/src/server/utils/request.ts @@ -138,7 +138,7 @@ const httpRequest = async ( ": error response :" + (errorResponse ? parseInt(errorResponse?.status, 10) : error?.message)) logger.error(":: ERROR STACK :: " + error?.stack || error); - logger.warn(`Error occurred while making request to ${getServiceName(_url)}: returning error response ${JSON.stringify(errorResponse?.data || { Errors: [{ code: error.message, description: error.stack }] })}`); + logger.warn(`Error occurred while making request to ${getServiceName(_url)}: with error response ${JSON.stringify(errorResponse?.data || { Errors: [{ code: error.message, description: error.stack }] })}`); if (retry) { attempt++; // Increment the attempt count if (attempt >= maxAttempts) {