const delay = require('delay'); const createDebug = require('debug'); const debug = createDebug('withRetry'); const getDelayForRetry = retry => 1000 * Math.pow(2, retry) + Math.random() * 100; const withRetry = (target, maxRetries = 5, shouldRetry = () => true) => { return async (...args) => { for (let retry = 0; retry < maxRetries - 1; retry++) { try { return await target(...args); } catch (error) { debug(error); if (!shouldRetry(error)) { break; } } await delay(getDelayForRetry(retry)); } return target(...args); }; }; module.exports = withRetry;