opusdev/vector-similarity-api
1
1'use strict';2 3import utils from '../utils.js';4import buildURL from '../helpers/buildURL.js';5import InterceptorManager from './InterceptorManager.js';6import dispatchRequest from './dispatchRequest.js';7import mergeConfig from './mergeConfig.js';8import buildFullPath from './buildFullPath.js';9import validator from '../helpers/validator.js';10import AxiosHeaders from './AxiosHeaders.js';11import transitionalDefaults from '../defaults/transitional.js';12 13const validators = validator.validators;14 15/**16 * Create a new instance of Axios17 *18 * @param {Object} instanceConfig The default config for the instance19 *20 * @return {Axios} A new instance of Axios21 */22class Axios {23 constructor(instanceConfig) {24 this.defaults = instanceConfig || {};25 this.interceptors = {26 request: new InterceptorManager(),27 response: new InterceptorManager()28 };29 }30 31 /**32 * Dispatch a request33 *34 * @param {String|Object} configOrUrl The config specific for this request (merged with this.defaults)35 * @param {?Object} config36 *37 * @returns {Promise} The Promise to be fulfilled38 */39 async request(configOrUrl, config) {40 try {41 return await this._request(configOrUrl, config);42 } catch (err) {43 if (err instanceof Error) {44 let dummy = {};45 46 Error.captureStackTrace ? Error.captureStackTrace(dummy) : (dummy = new Error());47 48 // slice off the Error: ... line49 const stack = dummy.stack ? dummy.stack.replace(/^.+\n/, '') : '';50 try {51 if (!err.stack) {52 err.stack = stack;53 // match without the 2 top stack lines54 } else if (stack && !String(err.stack).endsWith(stack.replace(/^.+\n.+\n/, ''))) {55 err.stack += '\n' + stack56 }57 } catch (e) {58 // ignore the case where "stack" is an un-writable property59 }60 }61 62 throw err;63 }64 }65 66 _request(configOrUrl, config) {67 /*eslint no-param-reassign:0*/68 // Allow for axios('example/url'[, config]) a la fetch API69 if (typeof configOrUrl === 'string') {70 config = config || {};71 config.url = configOrUrl;72 } else {73 config = configOrUrl || {};74 }75 76 config = mergeConfig(this.defaults, config);77 78 const {transitional, paramsSerializer, headers} = config;79 80 if (transitional !== undefined) {81 validator.assertOptions(transitional, {82 silentJSONParsing: validators.transitional(validators.boolean),83 forcedJSONParsing: validators.transitional(validators.boolean),84 clarifyTimeoutError: validators.transitional(validators.boolean),85 legacyInterceptorReqResOrdering: validators.transitional(validators.boolean)86 }, false);87 }88 89 if (paramsSerializer != null) {90 if (utils.isFunction(paramsSerializer)) {91 config.paramsSerializer = {92 serialize: paramsSerializer93 }94 } else {95 validator.assertOptions(paramsSerializer, {96 encode: validators.function,97 serialize: validators.function98 }, true);99 }100 }101 102 // Set config.allowAbsoluteUrls103 if (config.allowAbsoluteUrls !== undefined) {104 // do nothing105 } else if (this.defaults.allowAbsoluteUrls !== undefined) {106 config.allowAbsoluteUrls = this.defaults.allowAbsoluteUrls;107 } else {108 config.allowAbsoluteUrls = true;109 }110 111 validator.assertOptions(config, {112 baseUrl: validators.spelling('baseURL'),113 withXsrfToken: validators.spelling('withXSRFToken')114 }, true);115 116 // Set config.method117 config.method = (config.method || this.defaults.method || 'get').toLowerCase();118 119 // Flatten headers120 let contextHeaders = headers && utils.merge(121 headers.common,122 headers[config.method]123 );124 125 headers && utils.forEach(126 ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],127 (method) => {128 delete headers[method];129 }130 );131 132 config.headers = AxiosHeaders.concat(contextHeaders, headers);133 134 // filter out skipped interceptors135 const requestInterceptorChain = [];136 let synchronousRequestInterceptors = true;137 this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {138 if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) {139 return;140 }141 142 synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;143 144 const transitional = config.transitional || transitionalDefaults;145 const legacyInterceptorReqResOrdering = transitional && transitional.legacyInterceptorReqResOrdering;146 147 if (legacyInterceptorReqResOrdering) {148 requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);149 } else {150 requestInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);151 }152 });153 154 const responseInterceptorChain = [];155 this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {156 responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);157 });158 159 let promise;160 let i = 0;161 let len;162 163 if (!synchronousRequestInterceptors) {164 const chain = [dispatchRequest.bind(this), undefined];165 chain.unshift(...requestInterceptorChain);166 chain.push(...responseInterceptorChain);167 len = chain.length;168 169 promise = Promise.resolve(config);170 171 while (i < len) {172 promise = promise.then(chain[i++], chain[i++]);173 }174 175 return promise;176 }177 178 len = requestInterceptorChain.length;179 180 let newConfig = config;181 182 while (i < len) {183 const onFulfilled = requestInterceptorChain[i++];184 const onRejected = requestInterceptorChain[i++];185 try {186 newConfig = onFulfilled(newConfig);187 } catch (error) {188 onRejected.call(this, error);189 break;190 }191 }192 193 try {194 promise = dispatchRequest.call(this, newConfig);195 } catch (error) {196 return Promise.reject(error);197 }198 199 i = 0;200 len = responseInterceptorChain.length;201 202 while (i < len) {203 promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]);204 }205 206 return promise;207 }208 209 getUri(config) {210 config = mergeConfig(this.defaults, config);211 const fullPath = buildFullPath(config.baseURL, config.url, config.allowAbsoluteUrls);212 return buildURL(fullPath, config.params, config.paramsSerializer);213 }214}215 216// Provide aliases for supported request methods217utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {218 /*eslint func-names:0*/219 Axios.prototype[method] = function(url, config) {220 return this.request(mergeConfig(config || {}, {221 method,222 url,223 data: (config || {}).data224 }));225 };226});227 228utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {229 /*eslint func-names:0*/230 231 function generateHTTPMethod(isForm) {232 return function httpMethod(url, data, config) {233 return this.request(mergeConfig(config || {}, {234 method,235 headers: isForm ? {236 'Content-Type': 'multipart/form-data'237 } : {},238 url,239 data240 }));241 };242 }243 244 Axios.prototype[method] = generateHTTPMethod();245 246 Axios.prototype[method + 'Form'] = generateHTTPMethod(true);247});248 249export default Axios;250 