UNPKG

hud-ai

Version:
59 lines 2.51 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const _ = require("lodash"); const fp_1 = require("lodash/fp"); const Promise = require("bluebird"); const axios_1 = require("axios"); const qs = require("qs"); const https_1 = require("https"); const HudAiError_1 = require("./utils/HudAiError"); const clientVersion = require('../package.json').version; exports.defaultAxiosConfig = { headers: { 'User-Agent': `HUD.ai Javascript SDK v${clientVersion}` }, httpsAgent: new https_1.Agent({ keepAlive: true, rejectUnauthorized: true }), maxRedirects: 0, responseType: 'json', timeout: 10000, paramsSerializer: params => qs.stringify(params, { indices: true, strict: false, encode: true }) }; class RequestManager { constructor(client, config) { this.client = client; const axiosConfig = fp_1.flow(fp_1.merge({ baseURL: client.baseApiUrl }), fp_1.defaults(exports.defaultAxiosConfig))(config.request || {}); if (typeof window !== undefined) _.unset(axiosConfig, 'headers.User-Agent'); this.axios = axios_1.default.create(axiosConfig); } makeRequest(requestOptions, options = {}) { if (options.refreshTokens == undefined) options.refreshTokens = true; return Promise.resolve(options.refreshTokens ? this.client.refreshTokens() : undefined) .then(() => { const axiosOptions = this.buildAxiosOptions(requestOptions); const token = this.client.accessToken; if (token) _.set(axiosOptions, 'headers.Authorization', `Bearer ${token}`); return this.axios.request(axiosOptions); }) .then(response => response.data) .catch(err => { throw new HudAiError_1.HudAiError(err.message, err.type); }); } buildAxiosOptions(options) { const rawParams = options.params || {}; const urlParams = _.pickBy(rawParams, (value, key) => { return options.url.includes(`{${key}`); }); const queryParams = _.omit(rawParams, _.keys(urlParams)); return { data: options.data, method: options.method, params: queryParams, url: this.buildUrl(options.url, urlParams), }; } buildUrl(url, params = {}) { return _.reduce(params, (url, value, key) => _.replace(url, `{${key}}`, value), url); } } exports.RequestManager = RequestManager; //# sourceMappingURL=RequestManager.js.map