Skip to content

Instantly share code, notes, and snippets.

@Gimanua
Created January 28, 2021 23:14
Show Gist options
  • Save Gimanua/52e033307bc8a2510e53218d7f256e7e to your computer and use it in GitHub Desktop.
Save Gimanua/52e033307bc8a2510e53218d7f256e7e to your computer and use it in GitHub Desktop.
const util = require('util');
const axios = require('axios').default;
const customAxios = axios.create({
baseURL: 'http://localhost:3000',
headers: { 'Content-Type': 'application/json' }
});
const maxRetries = 5;
let currentRetry = 0;
function exponentialDelay(retry) {
return Math.pow(2, retry - 1) * 1000 + Math.random() * 1000;
}
function retryWithExponentialDelay(config, reason) {
currentRetry += 1;
if (currentRetry <= 5) {
const delay = Math.floor(exponentialDelay(currentRetry));
console.log(`Retrying in ${delay}ms due to ${reason}`);
return new Promise(resolve => {
setTimeout(() => {
resolve(customAxios.request(config));
}, delay);
});
}
else {
currentRetry = 0;
throw new Error(`Reached the maximum number of retries (${maxRetries}), last retry failed due to ${reason}`);
}
}
function onFulfilled(response) {
const items = response.data?.items;
if (items === undefined) {
return retryWithExponentialDelay(response.config, 'items not present');
}
else if(items.length === 0) {
return retryWithExponentialDelay(response.config, 'items list is empty');
}
currentRetry = 0;
return response;
}
function onRejected(error) {
return retryWithExponentialDelay(error.config, 'error response');
}
customAxios.interceptors.response.use(onFulfilled, onRejected);
async function generate() {
try {
const response = await customAxios.get('/example');
console.log(`Received response: ${util.inspect(response.data)}`);
} catch (error) {
if (error?.response?.data) console.log(`Encountered error: ${util.inspect(error.response.data)}`);
else if (error.message) console.log(error.message);
else console.log(`Encountered unknown error: ${util.inspect(error)}`);
}
}
generate();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment