-
Notifications
You must be signed in to change notification settings - Fork 22
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Update request.ts #928
Update request.ts #928
Changes from 2 commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change | ||||
---|---|---|---|---|---|---|
|
@@ -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); | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The error handling in the - const response = await httpRequest(searchUrl, searchBody, params, undefined, undefined, undefined, undefined, true);
+ const response = await httpRequest(searchUrl, searchBody, params ?? {}, undefined, undefined, undefined, undefined, true); Committable suggestion
Suggested change
|
||||||
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); | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Ensure that - var responsePayload = await httpRequest(createAndSearchConfig?.createBulkDetails?.url, newRequestBody, params, "post", undefined, undefined, true, true);
+ var responsePayload = await httpRequest(createAndSearchConfig?.createBulkDetails?.url, newRequestBody, params ?? {}, "post", undefined, undefined, true, true); Committable suggestion
Suggested change
ToolsBiome
|
||||||
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); | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The call to - const projectCreateResponse = await httpRequest(config.host.projectHost + config.paths.projectCreate, projectCreateBody, undefined, undefined, undefined, undefined, undefined, true);
+ const projectCreateResponse = await httpRequest(config.host.projectHost + config.paths.projectCreate, projectCreateBody, {}, undefined, undefined, undefined, undefined, true); Committable suggestion
Suggested change
|
||||||
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)) | ||||||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -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 | ||
Comment on lines
+672
to
+675
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Consider simplifying the function signature by removing unused parameters. - const staffResponse = await httpRequest(
- staffCreateUrl,
- resouceBody,
- undefined,
- "post",
- undefined,
- undefined,
- undefined,
- false,
- true
- );
+ const staffResponse = await httpRequest(staffCreateUrl, resouceBody, "post", false, true); The same refactoring can be applied to the Also applies to: 701-704, 730-733 |
||
); | ||
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 | ||
|
Original file line number | Diff line number | Diff line change | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
@@ -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,88 +65,115 @@ const httpRequest = async ( | |||||||||||||
_method: string = "post", | ||||||||||||||
responseType: string = "", | ||||||||||||||
headers: any = defaultheader, | ||||||||||||||
sendStatusCode: any = false | ||||||||||||||
sendStatusCode: any = false, | ||||||||||||||
retry: any = false, | ||||||||||||||
dontThrowError: any = false | ||||||||||||||
Comment on lines
+68
to
+70
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Ensure the new parameters - retry: any = false,
- dontThrowError: any = false
+ retry: boolean = false,
+ dontThrowError: boolean = false Committable suggestion
Suggested change
|
||||||||||||||
): Promise<any> => { | ||||||||||||||
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) { | ||||||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Use optional chaining to improve code safety and readability. - if (headers && headers.cachekey && cacheEnabled) {
+ if (headers?.cachekey && cacheEnabled) { Committable suggestion
Suggested change
ToolsBiome
|
||||||||||||||
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) | ||||||||||||||
); | ||||||||||||||
ashish-egov marked this conversation as resolved.
Show resolved
Hide resolved
|
||||||||||||||
} | ||||||||||||||
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) { | ||||||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Use optional chaining to simplify the condition. - if (headers && headers.cachekey) {
+ if (headers?.cachekey) { Committable suggestion
Suggested change
ToolsBiome
|
||||||||||||||
cacheResponse(response.data, headers.cachekey); | ||||||||||||||
} | ||||||||||||||
ashish-egov marked this conversation as resolved.
Show resolved
Hide resolved
|
||||||||||||||
// Return response data with status code if sendStatusCode flag is false | ||||||||||||||
if (!sendStatusCode) | ||||||||||||||
return response.data; | ||||||||||||||
else return { ...response.data, "statusCode": responseStatus }; | ||||||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Remove unnecessary else clause to enhance readability. - else return { ...response.data, "statusCode": responseStatus };
+ return !sendStatusCode ? response.data : { ...response.data, "statusCode": responseStatus }; Committable suggestion
Suggested change
ToolsBiome
|
||||||||||||||
} | ||||||||||||||
// 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 | ||||||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Declare 'var errorResponse' at the top of the function to follow best practices. + var errorResponse;
+ // rest of the function code
- var errorResponse = error?.response; // Get error response Committable suggestion
Suggested change
ToolsBiome
|
||||||||||||||
// 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 (retry) { | ||||||||||||||
attempt++; // Increment the attempt count | ||||||||||||||
if (attempt >= maxAttempts) { | ||||||||||||||
if (dontThrowError) { | ||||||||||||||
return errorResponse?.data || { Errors: [{ code: error.message, description: error.stack }] }; | ||||||||||||||
} | ||||||||||||||
else { | ||||||||||||||
throwTheHttpError(errorResponse, error, _url); | ||||||||||||||
} | ||||||||||||||
Comment on lines
+149
to
+151
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Remove unnecessary else clause to enhance readability. - else {
- throwTheHttpError(errorResponse, error, _url);
- }
+ throwTheHttpError(errorResponse, error, _url); Committable suggestion
Suggested change
ToolsBiome
|
||||||||||||||
} | ||||||||||||||
// 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 { | ||||||||||||||
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 |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Consider handling potential undefined values in the optional chaining in the
httpRequest
call.Committable suggestion