I'm calling an API which may respond with 200 response but still not contain the data I want, or it may throw an error. In both cases, I want to give it a retry for three times.
I've completed the task successfully but I'm using a continue statement in loop, in case I may get error so I don't want to return response but continue looping. How may I get rid of this continue statement?
const callApi = async (endpoint, commonParams = {}, params = {}, method = 'get', body = {}) => {
const logObject = {};
let url = 'https://partner.shopeemobile.com';
const timestamp = generalService.getTimestamp();
// Will attach to all requests
const editedCommanParams = { partner_id: +process.env.PARTNER_ID, timestamp, ...commonParams };
// sign also needs to be included in params
const sign = generateSign(endpoint, editedCommanParams);
const editedParams = { sign, ...params };
// query string will be attached to url regardless of request method
const allParams = Object.assign(editedCommanParams, editedParams);
const queryString = new URLSearchParams(allParams).toString();
url += `${endpoint}?${queryString}`;
const axiosData = { method, url };
if (method === 'post') {
axiosData.data = body;
}
logObject.RequestURL = url;
logObject.RequestData = JSON.stringify(body);
let failureCount = 0;
// loop calling the api
// This is where I need help
while (failureCount < 10) {
try {
const response = await axios(axiosData);
logObject.StatusCode = response.status;
logObject.ResponseData = JSON.stringify(response.data);
await generalService.insertQueryWithoutID(tables.REQRES, logObject);
if (response.data.error.length !== 0) {
failureCount += 1;
if (failureCount > 3) throw new Error('API Error');
continue; // need to get rid of this continue
}
return response.data;
} catch (error) {
// Errors maybe API errors which will be handled by error handler
// Sometimes errors are request specific those will be sent back to caller
if (typeof error.response !== 'undefined') {
logObject.StatusCode = error.response.status;
logObject.ResponseData = JSON.stringify(error.response.data);
} else {
logObject.StatusCode = 500;
logObject.ResponseData = JSON.stringify(error);
}
await generalService.insertQueryWithoutID(tables.REQRES, logObject);
failureCount += 1;
if (failureCount > 3) throw error;
}
}
};