UNPKG

@crowdin/crowdin-api-client

Version:
66 lines (65 loc) 2.14 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.AxiosProvider = void 0; const axios_1 = require("axios"); /** * @internal */ class AxiosProvider { constructor() { this.pendingRequests = 0; this.axios = axios_1.default.create({}); this.configureRequest(); this.configureResponse(); } withTimeout(timeout) { this.axios.defaults.timeout = timeout; return this; } get(url, config) { return this.unwrap(this.axios.get(url, config)); } delete(url, config) { return this.unwrap(this.axios.delete(url, config)); } head(url, config) { return this.unwrap(this.axios.head(url, config)); } post(url, data, config) { return this.unwrap(this.axios.post(url, data, config)); } put(url, data, config) { return this.unwrap(this.axios.put(url, data, config)); } patch(url, data, config) { return this.unwrap(this.axios.patch(url, data, config)); } async unwrap(request) { return (await request).data; } configureRequest() { this.axios.interceptors.request.use((config) => { return new Promise((resolve) => { const interval = setInterval(() => { if (this.pendingRequests < AxiosProvider.CROWDIN_API_MAX_CONCURRENT_REQUESTS) { this.pendingRequests++; clearInterval(interval); resolve(config); } }, AxiosProvider.CROWDIN_API_REQUESTS_INTERVAL_MS); }); }); } configureResponse() { this.axios.interceptors.response.use((response) => { this.pendingRequests = Math.max(0, this.pendingRequests - 1); return response; }, (error) => { this.pendingRequests = Math.max(0, this.pendingRequests - 1); return Promise.reject(error); }); } } exports.AxiosProvider = AxiosProvider; AxiosProvider.CROWDIN_API_MAX_CONCURRENT_REQUESTS = 15; AxiosProvider.CROWDIN_API_REQUESTS_INTERVAL_MS = 10;