@guilhermemj/insistent
Version:
A simple library to retry functions
46 lines • 2.33 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createInsistent = exports.insistOn = void 0;
function sleep(duration) {
return new Promise(r => setTimeout(r, duration));
}
function insistOn(targetFn, options = {}) {
var _a, _b, _c, _d;
return __awaiter(this, void 0, void 0, function* () {
const shouldRetry = (_a = options.retryWhen) !== null && _a !== void 0 ? _a : (() => true);
const retryCount = (_b = options.maxRetries) !== null && _b !== void 0 ? _b : 3;
const retryInterval = (_c = options.retryInterval) !== null && _c !== void 0 ? _c : 0;
const getNextInterval = (_d = options.incrementIntervalWith) !== null && _d !== void 0 ? _d : (last => last);
if (retryInterval < 0) {
throw new RangeError("retryInterval must be greater than or equal 0");
}
try {
// TODO: Call targetFn with some running metadata
return yield targetFn();
}
catch (error) {
if (retryCount <= 0 || !shouldRetry(error)) {
throw error;
}
if (retryInterval > 0) {
yield sleep(retryInterval);
}
return yield insistOn(targetFn, Object.assign(Object.assign({}, options), { maxRetries: retryCount - 1, retryInterval: getNextInterval(retryInterval) }));
}
});
}
exports.insistOn = insistOn;
function createInsistent(defaultOptions) {
return (fn, options = {}) => insistOn(fn, Object.assign(Object.assign({}, defaultOptions), options));
}
exports.createInsistent = createInsistent;
//# sourceMappingURL=index.js.map