Skip to content

Instantly share code, notes, and snippets.

@GendelfLugansk
Created February 26, 2019 23:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GendelfLugansk/c191d3c7fc0f46c80243fd18561aaaa4 to your computer and use it in GitHub Desktop.
Save GendelfLugansk/c191d3c7fc0f46c80243fd18561aaaa4 to your computer and use it in GitHub Desktop.
Simple function to retry requests using request-promise module
export default function(t) {
return new Promise(resolve => {
setTimeout(resolve, t);
});
}
import request from 'request-promise';
import wait from './awaitable-timeout';
function getTimeout(retryNumber, timeout) {
if (Array.isArray(timeout) && timeout.length > 0) {
return timeout.length >= retryNumber ? timeout[retryNumber - 1] : timeout[timeout.length - 1];
} else if (typeof timeout === 'number') {
return timeout;
}
return 0;
}
/**
* Make a request and retry in case of errors
*
* @param {{}} requestOptions Will be passed to request-promise
* @param {Number} retries Number of retries
* @param {Number[]|Number} timeout Number of milliseconds to wait before retrying
* @param requestTimeout Number of milliseconds. This will be passed to request as default option
* @return {Promise<void>}
*/
export default async function(
requestOptions,
{ retries = 10, timeout = [1000, 3000, 5000, 10000, 10000, 10000, 10000, 30000], requestTimeout = 60000 } = {}
) {
let retry = 0,
lastError;
while (retry <= retries) {
if (retry > 0) {
await wait(getTimeout(retry, timeout));
}
try {
return await request.defaults({ timeout: requestTimeout })(requestOptions);
} catch (err) {
if (
[
'ECONNRESET',
'ENOTFOUND',
'ESOCKETTIMEDOUT',
'ETIMEDOUT',
'ECONNREFUSED',
'EHOSTUNREACH',
'EPIPE',
'EAI_AGAIN',
'EINVAL',
].includes(err.cause.code) ||
err.statusCode === 429 ||
(500 <= err.statusCode && err.statusCode < 600)
) {
lastError = err;
retry++;
continue;
}
throw err;
}
}
throw lastError;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment