UNPKG

@cluelesscoders/request-pool

Version:

Create request pool queue for all types of http request

77 lines 2.53 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const axios_1 = __importDefault(require("axios")); class Response { constructor(request, response, duration) { this.error = response instanceof Error; this.response = response; this.request = request; this.duration = duration; } } exports.Response = Response; class RequestPool { constructor(targets, poolSize) { this.defaults = {}; this.responses = []; this.total = targets.length; this.targets = [...targets]; this.poolSize = poolSize; } setDefaults(options) { this.defaults = options; } /** * make requests and store responses * @param truth */ async processTask(truth) { const target = this.targets.shift(); if (!target) { return; } const options = Object.assign({}, target, this.defaults); const startTime = Date.now(); // make request and catch errors also const resp = await axios_1.default.request(options).catch((e) => e); const duration = RequestPool.prettyTime(Date.now() - startTime); // Add responses/errors and resolve promise chain when all fulfilled this.responses.push(new Response(options, resp, duration)); if (this.responses.length === this.total) { return truth.resolve(this.responses); } return this.processTask(truth); } /** * start the pool * @return Promise<Response[]> */ start() { return new Promise((resolve, reject) => { const truth = { resolve, reject }; if (!this.targets || this.targets.length === 0) { return reject(new Error('no targets found')); } const limit = Math.min(this.poolSize, this.targets.length); // fill pool with limit for (let i = 0; i < limit; i += 1) { this.targets[i] && this.processTask(truth); } }); } /** * convert time in ms or sec * @param duration */ static prettyTime(duration) { if (duration < 1000) return `${duration} ms`; /* istanbul ignore next */ return `${Math.floor(duration / 1000)} sec`; } } exports.RequestPool = RequestPool; //# sourceMappingURL=index.js.map