UNPKG

dash-core

Version:

A foundational toolkit of types, collections, services, and architectural patterns designed to accelerate application development.

74 lines (73 loc) 3.2 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.RestRequest = void 0; const axios_1 = __importDefault(require("axios")); const dash_core_1 = require("dash-core"); /** * Provides HTTP GET and POST requests with retries using exponential backoff. */ class RestRequest { throwException; backoff; /** * Creates an instance of the RestRequest class. * @param {boolean} [throwException=false] - Whether to throw the error after retries fail. If false, the promise will reject. * @param {ExponentialBackoffOptions} [backoffOption] - The configuration for the exponential backoff algorithm. * If not provided, defaults will be used (initial delay: 5 seconds, max delay: 30 seconds, factor: 2). */ constructor(throwException = false, backoffOption) { this.throwException = throwException; if (!backoffOption) backoffOption = { initialDelay: dash_core_1.TimeSpan.fromSeconds(5), maxDelay: dash_core_1.TimeSpan.fromSeconds(30), factor: 2 }; this.backoff = new dash_core_1.ExponentialBackoff(backoffOption); } /** * Makes an HTTP GET request to the specified URL with the optional configuration and retries on failure. * The request is retried using exponential backoff. * @param {string} url - The URL to send the GET request to. * @param {AxiosRequestConfig} [config] - The optional configuration for the GET request. * @returns {Promise<AxiosResponse<T>>} A promise that resolves with the response of the GET request. */ get(url, config) { return new Promise((resolve, reject) => { this.backoff.execute(() => axios_1.default.get(url, config)) .then((response) => { resolve(response); }) .catch((error) => { reject(error); if (this.throwException) throw error; }); }); } /** * Makes an HTTP POST request to the specified URL with the provided data and optional configuration and retries on failure. * The request is retried using exponential backoff. * @param {string} url - The URL to send the POST request to. * @param {any} [data] - The optional data to send in the body of the POST request. * @param {AxiosRequestConfig} [config] - The optional configuration for the POST request. * @returns {Promise<AxiosResponse<T>>} A promise that resolves with the response of the POST request. */ post(url, data, config) { return new Promise((resolve, reject) => { this.backoff.execute(() => axios_1.default.post(url, data, config)) .then((response) => { resolve(response); }) .catch((error) => { reject(error); if (this.throwException) throw error; }); }); } } exports.RestRequest = RestRequest;