UNPKG

@crowdin/crowdin-api-client

Version:
104 lines (103 loc) 3.34 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.FetchClient = void 0; const fetchClientError_1 = require("./fetchClientError"); /** * @internal */ class FetchClient { constructor() { this.maxConcurrentRequests = 15; this.requestIntervalMs = 10; this.pendingRequests = 0; } withTimeout(timeout) { this.timeout = timeout; return this; } get(url, config) { return this.request(url, 'GET', config); } delete(url, config) { return this.request(url, 'DELETE', config); } head(url, config) { return this.request(url, 'HEAD', config); } post(url, data, config) { return this.request(url, 'POST', config, data); } put(url, data, config) { return this.request(url, 'PUT', config, data); } patch(url, data, config) { return this.request(url, 'PATCH', config, data); } async request(url, method, config, data) { var _a; let body; if (data) { if (typeof data === 'object' && !this.isBuffer(data)) { body = JSON.stringify(data); config = config !== null && config !== void 0 ? config : { headers: {} }; config.headers = (_a = config.headers) !== null && _a !== void 0 ? _a : {}; config.headers['Content-Type'] = 'application/json'; } else { body = data; } } await this.waitInQueue(); let request; const headers = config ? config.headers : {}; if (this.timeout) { const controller = new AbortController(); const timeoutId = setTimeout(() => controller.abort(), this.timeout); request = fetch(url, { method, headers, body, signal: controller.signal }).then((res) => { clearTimeout(timeoutId); return res; }); } else { request = fetch(url, { method, headers, body }); } return request .then(async (res) => { if (res.status === 204) { return {}; } const text = await res.text(); const json = text ? JSON.parse(text) : {}; if (res.status >= 200 && res.status < 300) { return json; } else { throw new fetchClientError_1.FetchClientJsonPayloadError(res.statusText, json, res.status); } }) .finally(() => (this.pendingRequests = Math.max(0, this.pendingRequests - 1))); } isBuffer(data) { if (typeof ArrayBuffer === 'function') { return ArrayBuffer.isView(data); } else if (typeof Buffer === 'function') { return Buffer.isBuffer(data); } else { return false; } } waitInQueue() { return new Promise((resolve) => { const interval = setInterval(() => { if (this.pendingRequests < this.maxConcurrentRequests) { this.pendingRequests++; clearInterval(interval); resolve(); } }, this.requestIntervalMs); }); } } exports.FetchClient = FetchClient;