retryable-operation
Version:
a simple package that allow executing retryable operation and providing retry options
80 lines • 2.95 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.RetryableOperation = void 0;
const tslib_1 = require("tslib");
const result_1 = require("./result");
class RetryableOperation {
constructor(_options) {
var _a, _b, _c, _d, _e;
this.args = [];
this._errors = [];
this._attempts = 1;
this.shouldRetry = (err, attempts) => true;
this.retries = 3;
this.factor = 2;
this.maxDelay = 60 * 1000 * 1;
this.minDelay = 1000;
this.retries = (_a = _options.reties) !== null && _a !== void 0 ? _a : this.retries;
this.shouldRetry = _options.shouldRetry || this.shouldRetry;
this.fn = _options.fn;
this.factor = (_b = _options.factor) !== null && _b !== void 0 ? _b : this.factor;
this.args = (_c = _options.args) !== null && _c !== void 0 ? _c : this.args;
this._executor = _options.executor;
this.timeout = this.minDelay;
this.maxDelay = (_d = _options.maxDelay) !== null && _d !== void 0 ? _d : this.maxDelay;
this.minDelay = (_e = _options.minDelay) !== null && _e !== void 0 ? _e : this.minDelay;
}
attempt() {
return new Promise((resolve, reject) => tslib_1.__awaiter(this, void 0, void 0, function* () {
try {
const result = this._executor
? yield this._executor(this.fn)
: yield this.fn(...this.args);
resolve(Object.assign({ operationRef: this }, result_1.Result.Ok(result)));
}
catch (error) {
this._errors.push(error);
if (this.shouldRetry(error, this._attempts) &&
this._attempts < this.retries) {
this.timeout = Math.floor(Math.min(Math.random() *
this.minDelay *
Math.pow(this.factor, this.attempts), this.maxDelay));
setTimeout(() => {
this._attempts++;
resolve(this.attempt());
}, this.timeout);
}
else
resolve(Object.assign({ operationRef: this }, result_1.Result.Err(error)));
}
}));
}
setExecutor(executor) {
this._executor = executor;
return this;
}
setArgs(...args) {
this.args = args;
return this;
}
set executor(executor) {
this._executor = executor;
}
get options() {
return {
retries: this.retries,
factor: this.factor,
args: this.args,
maxDelay: this.maxDelay,
minDelay: this.minDelay,
};
}
get attempts() {
return this._attempts;
}
get errors() {
return this._errors;
}
}
exports.RetryableOperation = RetryableOperation;
//# sourceMappingURL=retryable-operation.js.map