mirror of
https://github.com/tenrok/axios.git
synced 2026-06-14 18:42:33 +03:00
Axios ES2017 (#4787)
* Added AxiosHeaders class; * Fixed README.md href; * Fixed a potential bug with headers normalization; * Fixed a potential bug with headers normalization; Refactored accessor building routine; Refactored default transforms; Removed `normalizeHeaderName` helper; * Added `Content-Length` accessor; Added missed `has` accessor to TS types; * Added `AxiosTransformStream` class; Added progress capturing ability for node.js environment; Added `maxRate` option to limit the data rate in node.js environment; Refactored event handled by `onUploadProgress` && `onDownloadProgress` listeners in browser environment; Added progress & data rate tests for the http adapter; Added response stream aborting test; Added a manual progress capture test for the browser; Updated TS types; Added TS tests; Refactored request abort logic for the http adapter; Added ability to abort the response stream; * Remove `stream/promises` & `timers/promises` modules usage in tests; * Use `abortcontroller-polyfill`; * Fixed AxiosTransformStream dead-lock in legacy node versions; Fixed CancelError emitting in streams; * Reworked AxiosTransformStream internal logic to optimize memory consumption; Added throwing an error if the request stream was silently destroying (without error) Refers to #3966; * Treat the destruction of the request stream as a cancellation of the request; Fixed tests; * Emit `progress` event in the next tick; * Initial refactoring; * Refactored Mocha tests to use ESM; * Refactored Karma tests to use rollup preprocessor & ESM; Replaced grunt with gulp; Improved dev scripts; Added Babel for rollup build; * Added default commonjs package export for Node build; Added automatic contributors list generator for package.json; Co-authored-by: Jay <jasonsaayman@gmail.com>
This commit is contained in:
+133
-110
@@ -1,14 +1,16 @@
|
||||
'use strict';
|
||||
|
||||
var utils = require('./../utils');
|
||||
var buildURL = require('../helpers/buildURL');
|
||||
var InterceptorManager = require('./InterceptorManager');
|
||||
var dispatchRequest = require('./dispatchRequest');
|
||||
var mergeConfig = require('./mergeConfig');
|
||||
var buildFullPath = require('./buildFullPath');
|
||||
var validator = require('../helpers/validator');
|
||||
import utils from './../utils.js';
|
||||
import buildURL from '../helpers/buildURL.js';
|
||||
import InterceptorManager from './InterceptorManager.js';
|
||||
import dispatchRequest from './dispatchRequest.js';
|
||||
import mergeConfig from './mergeConfig.js';
|
||||
import buildFullPath from './buildFullPath.js';
|
||||
import validator from '../helpers/validator.js';
|
||||
import AxiosHeaders from './AxiosHeaders.js';
|
||||
|
||||
const validators = validator.validators;
|
||||
|
||||
var validators = validator.validators;
|
||||
/**
|
||||
* Create a new instance of Axios
|
||||
*
|
||||
@@ -16,126 +18,147 @@ var validators = validator.validators;
|
||||
*
|
||||
* @return {Axios} A new instance of Axios
|
||||
*/
|
||||
function Axios(instanceConfig) {
|
||||
this.defaults = instanceConfig;
|
||||
this.interceptors = {
|
||||
request: new InterceptorManager(),
|
||||
response: new InterceptorManager()
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Dispatch a request
|
||||
*
|
||||
* @param {String|Object} configOrUrl The config specific for this request (merged with this.defaults)
|
||||
* @param {?Object} config
|
||||
*
|
||||
* @returns {Promise} The Promise to be fulfilled
|
||||
*/
|
||||
Axios.prototype.request = function request(configOrUrl, config) {
|
||||
/*eslint no-param-reassign:0*/
|
||||
// Allow for axios('example/url'[, config]) a la fetch API
|
||||
if (typeof configOrUrl === 'string') {
|
||||
config = config || {};
|
||||
config.url = configOrUrl;
|
||||
} else {
|
||||
config = configOrUrl || {};
|
||||
class Axios {
|
||||
constructor(instanceConfig) {
|
||||
this.defaults = instanceConfig;
|
||||
this.interceptors = {
|
||||
request: new InterceptorManager(),
|
||||
response: new InterceptorManager()
|
||||
};
|
||||
}
|
||||
|
||||
config = mergeConfig(this.defaults, config);
|
||||
|
||||
// Set config.method
|
||||
if (config.method) {
|
||||
config.method = config.method.toLowerCase();
|
||||
} else if (this.defaults.method) {
|
||||
config.method = this.defaults.method.toLowerCase();
|
||||
} else {
|
||||
config.method = 'get';
|
||||
}
|
||||
|
||||
var transitional = config.transitional;
|
||||
|
||||
if (transitional !== undefined) {
|
||||
validator.assertOptions(transitional, {
|
||||
silentJSONParsing: validators.transitional(validators.boolean),
|
||||
forcedJSONParsing: validators.transitional(validators.boolean),
|
||||
clarifyTimeoutError: validators.transitional(validators.boolean)
|
||||
}, false);
|
||||
}
|
||||
|
||||
// filter out skipped interceptors
|
||||
var requestInterceptorChain = [];
|
||||
var synchronousRequestInterceptors = true;
|
||||
this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
|
||||
if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) {
|
||||
return;
|
||||
/**
|
||||
* Dispatch a request
|
||||
*
|
||||
* @param {String|Object} configOrUrl The config specific for this request (merged with this.defaults)
|
||||
* @param {?Object} config
|
||||
*
|
||||
* @returns {Promise} The Promise to be fulfilled
|
||||
*/
|
||||
request(configOrUrl, config) {
|
||||
/*eslint no-param-reassign:0*/
|
||||
// Allow for axios('example/url'[, config]) a la fetch API
|
||||
if (typeof configOrUrl === 'string') {
|
||||
config = config || {};
|
||||
config.url = configOrUrl;
|
||||
} else {
|
||||
config = configOrUrl || {};
|
||||
}
|
||||
|
||||
synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;
|
||||
config = mergeConfig(this.defaults, config);
|
||||
|
||||
requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);
|
||||
});
|
||||
const transitional = config.transitional;
|
||||
|
||||
var responseInterceptorChain = [];
|
||||
this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
|
||||
responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
|
||||
});
|
||||
if (transitional !== undefined) {
|
||||
validator.assertOptions(transitional, {
|
||||
silentJSONParsing: validators.transitional(validators.boolean),
|
||||
forcedJSONParsing: validators.transitional(validators.boolean),
|
||||
clarifyTimeoutError: validators.transitional(validators.boolean)
|
||||
}, false);
|
||||
}
|
||||
|
||||
var promise;
|
||||
// Set config.method
|
||||
config.method = (config.method || this.defaults.method || 'get').toLowerCase();
|
||||
|
||||
if (!synchronousRequestInterceptors) {
|
||||
var chain = [dispatchRequest, undefined];
|
||||
// Flatten headers
|
||||
const defaultHeaders = config.headers && utils.merge(
|
||||
config.headers.common,
|
||||
config.headers[config.method]
|
||||
);
|
||||
|
||||
Array.prototype.unshift.apply(chain, requestInterceptorChain);
|
||||
chain = chain.concat(responseInterceptorChain);
|
||||
defaultHeaders && utils.forEach(
|
||||
['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],
|
||||
function cleanHeaderConfig(method) {
|
||||
delete config.headers[method];
|
||||
}
|
||||
);
|
||||
|
||||
promise = Promise.resolve(config);
|
||||
while (chain.length) {
|
||||
promise = promise.then(chain.shift(), chain.shift());
|
||||
config.headers = new AxiosHeaders(config.headers, defaultHeaders);
|
||||
|
||||
// filter out skipped interceptors
|
||||
const requestInterceptorChain = [];
|
||||
let synchronousRequestInterceptors = true;
|
||||
this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
|
||||
if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) {
|
||||
return;
|
||||
}
|
||||
|
||||
synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;
|
||||
|
||||
requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);
|
||||
});
|
||||
|
||||
const responseInterceptorChain = [];
|
||||
this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
|
||||
responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
|
||||
});
|
||||
|
||||
let promise;
|
||||
let i = 0;
|
||||
let len;
|
||||
|
||||
if (!synchronousRequestInterceptors) {
|
||||
const chain = [dispatchRequest.bind(this), undefined];
|
||||
chain.unshift.apply(chain, requestInterceptorChain);
|
||||
chain.push.apply(chain, responseInterceptorChain);
|
||||
len = chain.length;
|
||||
|
||||
promise = Promise.resolve(config);
|
||||
|
||||
while (i < len) {
|
||||
promise = promise.then(chain[i++], chain[i++]);
|
||||
}
|
||||
|
||||
return promise;
|
||||
}
|
||||
|
||||
len = requestInterceptorChain.length;
|
||||
|
||||
let newConfig = config;
|
||||
|
||||
i = 0;
|
||||
|
||||
while (i < len) {
|
||||
const onFulfilled = requestInterceptorChain[i++];
|
||||
const onRejected = requestInterceptorChain[i++];
|
||||
try {
|
||||
newConfig = onFulfilled(newConfig);
|
||||
} catch (error) {
|
||||
onRejected.call(this, error);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
promise = dispatchRequest.call(this, newConfig);
|
||||
} catch (error) {
|
||||
return Promise.reject(error);
|
||||
}
|
||||
|
||||
i = 0;
|
||||
len = responseInterceptorChain.length;
|
||||
|
||||
while (i < len) {
|
||||
promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]);
|
||||
}
|
||||
|
||||
return promise;
|
||||
}
|
||||
|
||||
|
||||
var newConfig = config;
|
||||
while (requestInterceptorChain.length) {
|
||||
var onFulfilled = requestInterceptorChain.shift();
|
||||
var onRejected = requestInterceptorChain.shift();
|
||||
try {
|
||||
newConfig = onFulfilled(newConfig);
|
||||
} catch (error) {
|
||||
onRejected(error);
|
||||
break;
|
||||
}
|
||||
getUri(config) {
|
||||
config = mergeConfig(this.defaults, config);
|
||||
const fullPath = buildFullPath(config.baseURL, config.url);
|
||||
return buildURL(fullPath, config.params, config.paramsSerializer);
|
||||
}
|
||||
|
||||
try {
|
||||
promise = dispatchRequest(newConfig);
|
||||
} catch (error) {
|
||||
return Promise.reject(error);
|
||||
}
|
||||
|
||||
while (responseInterceptorChain.length) {
|
||||
promise = promise.then(responseInterceptorChain.shift(), responseInterceptorChain.shift());
|
||||
}
|
||||
|
||||
return promise;
|
||||
};
|
||||
|
||||
Axios.prototype.getUri = function getUri(config) {
|
||||
config = mergeConfig(this.defaults, config);
|
||||
var fullPath = buildFullPath(config.baseURL, config.url);
|
||||
return buildURL(fullPath, config.params, config.paramsSerializer);
|
||||
};
|
||||
}
|
||||
|
||||
// Provide aliases for supported request methods
|
||||
utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {
|
||||
/*eslint func-names:0*/
|
||||
Axios.prototype[method] = function(url, config) {
|
||||
return this.request(mergeConfig(config || {}, {
|
||||
method: method,
|
||||
url: url,
|
||||
method,
|
||||
url,
|
||||
data: (config || {}).data
|
||||
}));
|
||||
};
|
||||
@@ -147,12 +170,12 @@ utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
|
||||
function generateHTTPMethod(isForm) {
|
||||
return function httpMethod(url, data, config) {
|
||||
return this.request(mergeConfig(config || {}, {
|
||||
method: method,
|
||||
method,
|
||||
headers: isForm ? {
|
||||
'Content-Type': 'multipart/form-data'
|
||||
} : {},
|
||||
url: url,
|
||||
data: data
|
||||
url,
|
||||
data
|
||||
}));
|
||||
};
|
||||
}
|
||||
@@ -162,4 +185,4 @@ utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
|
||||
Axios.prototype[method + 'Form'] = generateHTTPMethod(true);
|
||||
});
|
||||
|
||||
module.exports = Axios;
|
||||
export default Axios;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
'use strict';
|
||||
|
||||
var utils = require('../utils');
|
||||
import utils from '../utils.js';
|
||||
|
||||
/**
|
||||
* Create an Error with the specified message, config, error code, request and response.
|
||||
@@ -52,8 +52,8 @@ utils.inherits(AxiosError, Error, {
|
||||
}
|
||||
});
|
||||
|
||||
var prototype = AxiosError.prototype;
|
||||
var descriptors = {};
|
||||
const prototype = AxiosError.prototype;
|
||||
const descriptors = {};
|
||||
|
||||
[
|
||||
'ERR_BAD_OPTION_VALUE',
|
||||
@@ -69,7 +69,7 @@ var descriptors = {};
|
||||
'ERR_NOT_SUPPORT',
|
||||
'ERR_INVALID_URL'
|
||||
// eslint-disable-next-line func-names
|
||||
].forEach(function(code) {
|
||||
].forEach(code => {
|
||||
descriptors[code] = {value: code};
|
||||
});
|
||||
|
||||
@@ -77,11 +77,13 @@ Object.defineProperties(AxiosError, descriptors);
|
||||
Object.defineProperty(prototype, 'isAxiosError', {value: true});
|
||||
|
||||
// eslint-disable-next-line func-names
|
||||
AxiosError.from = function(error, code, config, request, response, customProps) {
|
||||
var axiosError = Object.create(prototype);
|
||||
AxiosError.from = (error, code, config, request, response, customProps) => {
|
||||
const axiosError = Object.create(prototype);
|
||||
|
||||
utils.toFlatObject(error, axiosError, function filter(obj) {
|
||||
return obj !== Error.prototype;
|
||||
}, prop => {
|
||||
return prop !== 'isAxiosError';
|
||||
});
|
||||
|
||||
AxiosError.call(axiosError, error.message, code, config, request, response);
|
||||
@@ -95,4 +97,4 @@ AxiosError.from = function(error, code, config, request, response, customProps)
|
||||
return axiosError;
|
||||
};
|
||||
|
||||
module.exports = AxiosError;
|
||||
export default AxiosError;
|
||||
|
||||
@@ -0,0 +1,274 @@
|
||||
'use strict';
|
||||
|
||||
import utils from '../utils.js';
|
||||
import parseHeaders from '../helpers/parseHeaders.js';
|
||||
|
||||
const $internals = Symbol('internals');
|
||||
const $defaults = Symbol('defaults');
|
||||
|
||||
function normalizeHeader(header) {
|
||||
return header && String(header).trim().toLowerCase();
|
||||
}
|
||||
|
||||
function normalizeValue(value) {
|
||||
if (value === false || value == null) {
|
||||
return value;
|
||||
}
|
||||
|
||||
return String(value);
|
||||
}
|
||||
|
||||
function parseTokens(str) {
|
||||
const tokens = Object.create(null);
|
||||
const tokensRE = /([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;
|
||||
let match;
|
||||
|
||||
while ((match = tokensRE.exec(str))) {
|
||||
tokens[match[1]] = match[2];
|
||||
}
|
||||
|
||||
return tokens;
|
||||
}
|
||||
|
||||
function matchHeaderValue(context, value, header, filter) {
|
||||
if (utils.isFunction(filter)) {
|
||||
return filter.call(this, value, header);
|
||||
}
|
||||
|
||||
if (!utils.isString(value)) return;
|
||||
|
||||
if (utils.isString(filter)) {
|
||||
return value.indexOf(filter) !== -1;
|
||||
}
|
||||
|
||||
if (utils.isRegExp(filter)) {
|
||||
return filter.test(value);
|
||||
}
|
||||
}
|
||||
|
||||
function formatHeader(header) {
|
||||
return header.trim()
|
||||
.toLowerCase().replace(/([a-z\d])(\w*)/g, (w, char, str) => {
|
||||
return char.toUpperCase() + str;
|
||||
});
|
||||
}
|
||||
|
||||
function buildAccessors(obj, header) {
|
||||
const accessorName = utils.toCamelCase(' ' + header);
|
||||
|
||||
['get', 'set', 'has'].forEach(methodName => {
|
||||
Object.defineProperty(obj, methodName + accessorName, {
|
||||
value: function(arg1, arg2, arg3) {
|
||||
return this[methodName].call(this, header, arg1, arg2, arg3);
|
||||
},
|
||||
configurable: true
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function findKey(obj, key) {
|
||||
key = key.toLowerCase();
|
||||
const keys = Object.keys(obj);
|
||||
let i = keys.length;
|
||||
let _key;
|
||||
while (i-- > 0) {
|
||||
_key = keys[i];
|
||||
if (key === _key.toLowerCase()) {
|
||||
return _key;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function AxiosHeaders(headers, defaults) {
|
||||
headers && this.set(headers);
|
||||
this[$defaults] = defaults || null;
|
||||
}
|
||||
|
||||
Object.assign(AxiosHeaders.prototype, {
|
||||
set: function(header, valueOrRewrite, rewrite) {
|
||||
const self = this;
|
||||
|
||||
function setHeader(_value, _header, _rewrite) {
|
||||
const lHeader = normalizeHeader(_header);
|
||||
|
||||
if (!lHeader) {
|
||||
throw new Error('header name must be a non-empty string');
|
||||
}
|
||||
|
||||
const key = findKey(self, lHeader);
|
||||
|
||||
if (key && _rewrite !== true && (self[key] === false || _rewrite === false)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (utils.isArray(_value)) {
|
||||
_value = _value.map(normalizeValue);
|
||||
} else {
|
||||
_value = normalizeValue(_value);
|
||||
}
|
||||
|
||||
self[key || _header] = _value;
|
||||
}
|
||||
|
||||
if (utils.isPlainObject(header)) {
|
||||
utils.forEach(header, (_value, _header) => {
|
||||
setHeader(_value, _header, valueOrRewrite);
|
||||
});
|
||||
} else {
|
||||
setHeader(valueOrRewrite, header, rewrite);
|
||||
}
|
||||
|
||||
return this;
|
||||
},
|
||||
|
||||
get: function(header, parser) {
|
||||
header = normalizeHeader(header);
|
||||
|
||||
if (!header) return undefined;
|
||||
|
||||
const key = findKey(this, header);
|
||||
|
||||
if (key) {
|
||||
const value = this[key];
|
||||
|
||||
if (!parser) {
|
||||
return value;
|
||||
}
|
||||
|
||||
if (parser === true) {
|
||||
return parseTokens(value);
|
||||
}
|
||||
|
||||
if (utils.isFunction(parser)) {
|
||||
return parser.call(this, value, key);
|
||||
}
|
||||
|
||||
if (utils.isRegExp(parser)) {
|
||||
return parser.exec(value);
|
||||
}
|
||||
|
||||
throw new TypeError('parser must be boolean|regexp|function');
|
||||
}
|
||||
},
|
||||
|
||||
has: function(header, matcher) {
|
||||
header = normalizeHeader(header);
|
||||
|
||||
if (header) {
|
||||
const key = findKey(this, header);
|
||||
|
||||
return !!(key && (!matcher || matchHeaderValue(this, this[key], key, matcher)));
|
||||
}
|
||||
|
||||
return false;
|
||||
},
|
||||
|
||||
delete: function(header, matcher) {
|
||||
const self = this;
|
||||
let deleted = false;
|
||||
|
||||
function deleteHeader(_header) {
|
||||
_header = normalizeHeader(_header);
|
||||
|
||||
if (_header) {
|
||||
const key = findKey(self, _header);
|
||||
|
||||
if (key && (!matcher || matchHeaderValue(self, self[key], key, matcher))) {
|
||||
delete self[key];
|
||||
|
||||
deleted = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (utils.isArray(header)) {
|
||||
header.forEach(deleteHeader);
|
||||
} else {
|
||||
deleteHeader(header);
|
||||
}
|
||||
|
||||
return deleted;
|
||||
},
|
||||
|
||||
clear: function() {
|
||||
return Object.keys(this).forEach(this.delete.bind(this));
|
||||
},
|
||||
|
||||
normalize: function(format) {
|
||||
const self = this;
|
||||
const headers = {};
|
||||
|
||||
utils.forEach(this, (value, header) => {
|
||||
const key = findKey(headers, header);
|
||||
|
||||
if (key) {
|
||||
self[key] = normalizeValue(value);
|
||||
delete self[header];
|
||||
return;
|
||||
}
|
||||
|
||||
const normalized = format ? formatHeader(header) : String(header).trim();
|
||||
|
||||
if (normalized !== header) {
|
||||
delete self[header];
|
||||
}
|
||||
|
||||
self[normalized] = normalizeValue(value);
|
||||
|
||||
headers[normalized] = true;
|
||||
});
|
||||
|
||||
return this;
|
||||
},
|
||||
|
||||
toJSON: function() {
|
||||
const obj = Object.create(null);
|
||||
|
||||
utils.forEach(Object.assign({}, this[$defaults] || null, this),
|
||||
(value, header) => {
|
||||
if (value == null || value === false) return;
|
||||
obj[header] = utils.isArray(value) ? value.join(', ') : value;
|
||||
});
|
||||
|
||||
return obj;
|
||||
}
|
||||
});
|
||||
|
||||
Object.assign(AxiosHeaders, {
|
||||
from: function(thing) {
|
||||
if (utils.isString(thing)) {
|
||||
return new this(parseHeaders(thing));
|
||||
}
|
||||
return thing instanceof this ? thing : new this(thing);
|
||||
},
|
||||
|
||||
accessor: function(header) {
|
||||
const internals = this[$internals] = (this[$internals] = {
|
||||
accessors: {}
|
||||
});
|
||||
|
||||
const accessors = internals.accessors;
|
||||
const prototype = this.prototype;
|
||||
|
||||
function defineAccessor(_header) {
|
||||
const lHeader = normalizeHeader(_header);
|
||||
|
||||
if (!accessors[lHeader]) {
|
||||
buildAccessors(prototype, _header);
|
||||
accessors[lHeader] = true;
|
||||
}
|
||||
}
|
||||
|
||||
utils.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header);
|
||||
|
||||
return this;
|
||||
}
|
||||
});
|
||||
|
||||
AxiosHeaders.accessor(['Content-Type', 'Content-Length', 'Accept', 'Accept-Encoding', 'User-Agent']);
|
||||
|
||||
utils.freezeMethods(AxiosHeaders.prototype);
|
||||
utils.freezeMethods(AxiosHeaders);
|
||||
|
||||
export default AxiosHeaders;
|
||||
@@ -1,69 +1,71 @@
|
||||
'use strict';
|
||||
|
||||
var utils = require('./../utils');
|
||||
import utils from './../utils.js';
|
||||
|
||||
function InterceptorManager() {
|
||||
this.handlers = [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a new interceptor to the stack
|
||||
*
|
||||
* @param {Function} fulfilled The function to handle `then` for a `Promise`
|
||||
* @param {Function} rejected The function to handle `reject` for a `Promise`
|
||||
*
|
||||
* @return {Number} An ID used to remove interceptor later
|
||||
*/
|
||||
InterceptorManager.prototype.use = function use(fulfilled, rejected, options) {
|
||||
this.handlers.push({
|
||||
fulfilled: fulfilled,
|
||||
rejected: rejected,
|
||||
synchronous: options ? options.synchronous : false,
|
||||
runWhen: options ? options.runWhen : null
|
||||
});
|
||||
return this.handlers.length - 1;
|
||||
};
|
||||
|
||||
/**
|
||||
* Remove an interceptor from the stack
|
||||
*
|
||||
* @param {Number} id The ID that was returned by `use`
|
||||
*
|
||||
* @returns {Boolean} `true` if the interceptor was removed, `false` otherwise
|
||||
*/
|
||||
InterceptorManager.prototype.eject = function eject(id) {
|
||||
if (this.handlers[id]) {
|
||||
this.handlers[id] = null;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Clear all interceptors from the stack
|
||||
*
|
||||
* @returns {void}
|
||||
*/
|
||||
InterceptorManager.prototype.clear = function clear() {
|
||||
if (this.handlers) {
|
||||
class InterceptorManager {
|
||||
constructor() {
|
||||
this.handlers = [];
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Iterate over all the registered interceptors
|
||||
*
|
||||
* This method is particularly useful for skipping over any
|
||||
* interceptors that may have become `null` calling `eject`.
|
||||
*
|
||||
* @param {Function} fn The function to call for each interceptor
|
||||
*
|
||||
* @returns {void}
|
||||
*/
|
||||
InterceptorManager.prototype.forEach = function forEach(fn) {
|
||||
utils.forEach(this.handlers, function forEachHandler(h) {
|
||||
if (h !== null) {
|
||||
fn(h);
|
||||
/**
|
||||
* Add a new interceptor to the stack
|
||||
*
|
||||
* @param {Function} fulfilled The function to handle `then` for a `Promise`
|
||||
* @param {Function} rejected The function to handle `reject` for a `Promise`
|
||||
*
|
||||
* @return {Number} An ID used to remove interceptor later
|
||||
*/
|
||||
use(fulfilled, rejected, options) {
|
||||
this.handlers.push({
|
||||
fulfilled,
|
||||
rejected,
|
||||
synchronous: options ? options.synchronous : false,
|
||||
runWhen: options ? options.runWhen : null
|
||||
});
|
||||
return this.handlers.length - 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove an interceptor from the stack
|
||||
*
|
||||
* @param {Number} id The ID that was returned by `use`
|
||||
*
|
||||
* @returns {Boolean} `true` if the interceptor was removed, `false` otherwise
|
||||
*/
|
||||
eject(id) {
|
||||
if (this.handlers[id]) {
|
||||
this.handlers[id] = null;
|
||||
}
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = InterceptorManager;
|
||||
/**
|
||||
* Clear all interceptors from the stack
|
||||
*
|
||||
* @returns {void}
|
||||
*/
|
||||
clear() {
|
||||
if (this.handlers) {
|
||||
this.handlers = [];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Iterate over all the registered interceptors
|
||||
*
|
||||
* This method is particularly useful for skipping over any
|
||||
* interceptors that may have become `null` calling `eject`.
|
||||
*
|
||||
* @param {Function} fn The function to call for each interceptor
|
||||
*
|
||||
* @returns {void}
|
||||
*/
|
||||
forEach(fn) {
|
||||
utils.forEach(this.handlers, function forEachHandler(h) {
|
||||
if (h !== null) {
|
||||
fn(h);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export default InterceptorManager;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
'use strict';
|
||||
|
||||
var isAbsoluteURL = require('../helpers/isAbsoluteURL');
|
||||
var combineURLs = require('../helpers/combineURLs');
|
||||
import isAbsoluteURL from '../helpers/isAbsoluteURL.js';
|
||||
import combineURLs from '../helpers/combineURLs.js';
|
||||
|
||||
/**
|
||||
* Creates a new URL by combining the baseURL with the requestedURL,
|
||||
@@ -13,9 +13,9 @@ var combineURLs = require('../helpers/combineURLs');
|
||||
*
|
||||
* @returns {string} The combined full path
|
||||
*/
|
||||
module.exports = function buildFullPath(baseURL, requestedURL) {
|
||||
export default function buildFullPath(baseURL, requestedURL) {
|
||||
if (baseURL && !isAbsoluteURL(requestedURL)) {
|
||||
return combineURLs(baseURL, requestedURL);
|
||||
}
|
||||
return requestedURL;
|
||||
};
|
||||
}
|
||||
|
||||
+16
-39
@@ -1,11 +1,10 @@
|
||||
'use strict';
|
||||
|
||||
var utils = require('./../utils');
|
||||
var transformData = require('./transformData');
|
||||
var isCancel = require('../cancel/isCancel');
|
||||
var defaults = require('../defaults');
|
||||
var CanceledError = require('../cancel/CanceledError');
|
||||
var normalizeHeaderName = require('../helpers/normalizeHeaderName');
|
||||
import transformData from './transformData.js';
|
||||
import isCancel from '../cancel/isCancel.js';
|
||||
import defaults from '../defaults/index.js';
|
||||
import CanceledError from '../cancel/CanceledError.js';
|
||||
import AxiosHeaders from '../core/AxiosHeaders.js';
|
||||
|
||||
/**
|
||||
* Throws a `CanceledError` if cancellation has been requested.
|
||||
@@ -31,39 +30,18 @@ function throwIfCancellationRequested(config) {
|
||||
*
|
||||
* @returns {Promise} The Promise to be fulfilled
|
||||
*/
|
||||
module.exports = function dispatchRequest(config) {
|
||||
export default function dispatchRequest(config) {
|
||||
throwIfCancellationRequested(config);
|
||||
|
||||
// Ensure headers exist
|
||||
config.headers = config.headers || {};
|
||||
config.headers = AxiosHeaders.from(config.headers);
|
||||
|
||||
// Transform request data
|
||||
config.data = transformData.call(
|
||||
config,
|
||||
config.data,
|
||||
config.headers,
|
||||
null,
|
||||
config.transformRequest
|
||||
);
|
||||
|
||||
normalizeHeaderName(config.headers, 'Accept');
|
||||
normalizeHeaderName(config.headers, 'Content-Type');
|
||||
|
||||
// Flatten headers
|
||||
config.headers = utils.merge(
|
||||
config.headers.common || {},
|
||||
config.headers[config.method] || {},
|
||||
config.headers
|
||||
);
|
||||
|
||||
utils.forEach(
|
||||
['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],
|
||||
function cleanHeaderConfig(method) {
|
||||
delete config.headers[method];
|
||||
}
|
||||
);
|
||||
|
||||
var adapter = config.adapter || defaults.adapter;
|
||||
const adapter = config.adapter || defaults.adapter;
|
||||
|
||||
return adapter(config).then(function onAdapterResolution(response) {
|
||||
throwIfCancellationRequested(config);
|
||||
@@ -71,12 +49,12 @@ module.exports = function dispatchRequest(config) {
|
||||
// Transform response data
|
||||
response.data = transformData.call(
|
||||
config,
|
||||
response.data,
|
||||
response.headers,
|
||||
response.status,
|
||||
config.transformResponse
|
||||
config.transformResponse,
|
||||
response
|
||||
);
|
||||
|
||||
response.headers = AxiosHeaders.from(response.headers);
|
||||
|
||||
return response;
|
||||
}, function onAdapterRejection(reason) {
|
||||
if (!isCancel(reason)) {
|
||||
@@ -86,14 +64,13 @@ module.exports = function dispatchRequest(config) {
|
||||
if (reason && reason.response) {
|
||||
reason.response.data = transformData.call(
|
||||
config,
|
||||
reason.response.data,
|
||||
reason.response.headers,
|
||||
reason.response.status,
|
||||
config.transformResponse
|
||||
config.transformResponse,
|
||||
reason.response
|
||||
);
|
||||
reason.response.headers = AxiosHeaders.from(reason.response.headers);
|
||||
}
|
||||
}
|
||||
|
||||
return Promise.reject(reason);
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
'use strict';
|
||||
|
||||
var utils = require('../utils');
|
||||
import utils from '../utils.js';
|
||||
|
||||
/**
|
||||
* Config-specific merge-function which creates a new config-object
|
||||
@@ -11,10 +11,10 @@ var utils = require('../utils');
|
||||
*
|
||||
* @returns {Object} New object resulting from merging config2 to config1
|
||||
*/
|
||||
module.exports = function mergeConfig(config1, config2) {
|
||||
export default function mergeConfig(config1, config2) {
|
||||
// eslint-disable-next-line no-param-reassign
|
||||
config2 = config2 || {};
|
||||
var config = {};
|
||||
const config = {};
|
||||
|
||||
function getMergedValue(target, source) {
|
||||
if (utils.isPlainObject(target) && utils.isPlainObject(source)) {
|
||||
@@ -61,7 +61,7 @@ module.exports = function mergeConfig(config1, config2) {
|
||||
}
|
||||
}
|
||||
|
||||
var mergeMap = {
|
||||
const mergeMap = {
|
||||
'url': valueFromConfig2,
|
||||
'method': valueFromConfig2,
|
||||
'data': valueFromConfig2,
|
||||
@@ -92,10 +92,10 @@ module.exports = function mergeConfig(config1, config2) {
|
||||
};
|
||||
|
||||
utils.forEach(Object.keys(config1).concat(Object.keys(config2)), function computeConfigValue(prop) {
|
||||
var merge = mergeMap[prop] || mergeDeepProperties;
|
||||
var configValue = merge(prop);
|
||||
const merge = mergeMap[prop] || mergeDeepProperties;
|
||||
const configValue = merge(prop);
|
||||
(utils.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue);
|
||||
});
|
||||
|
||||
return config;
|
||||
};
|
||||
}
|
||||
|
||||
+4
-4
@@ -1,6 +1,6 @@
|
||||
'use strict';
|
||||
|
||||
var AxiosError = require('./AxiosError');
|
||||
import AxiosError from './AxiosError.js';
|
||||
|
||||
/**
|
||||
* Resolve or reject a Promise based on response status.
|
||||
@@ -11,8 +11,8 @@ var AxiosError = require('./AxiosError');
|
||||
*
|
||||
* @returns {object} The response.
|
||||
*/
|
||||
module.exports = function settle(resolve, reject, response) {
|
||||
var validateStatus = response.config.validateStatus;
|
||||
export default function settle(resolve, reject, response) {
|
||||
const validateStatus = response.config.validateStatus;
|
||||
if (!response.status || !validateStatus || validateStatus(response.status)) {
|
||||
resolve(response);
|
||||
} else {
|
||||
@@ -24,4 +24,4 @@ module.exports = function settle(resolve, reject, response) {
|
||||
response
|
||||
));
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
+14
-10
@@ -1,24 +1,28 @@
|
||||
'use strict';
|
||||
|
||||
var utils = require('./../utils');
|
||||
var defaults = require('../defaults');
|
||||
import utils from './../utils.js';
|
||||
import defaults from '../defaults/index.js';
|
||||
import AxiosHeaders from '../core/AxiosHeaders.js';
|
||||
|
||||
/**
|
||||
* Transform the data for a request or a response
|
||||
*
|
||||
* @param {Object|String} data The data to be transformed
|
||||
* @param {Array} headers The headers for the request or response
|
||||
* @param {Number} status HTTP status code
|
||||
* @param {Array|Function} fns A single function or Array of functions
|
||||
* @param {?Object} response The response object
|
||||
*
|
||||
* @returns {*} The resulting transformed data
|
||||
*/
|
||||
module.exports = function transformData(data, headers, status, fns) {
|
||||
var context = this || defaults;
|
||||
/*eslint no-param-reassign:0*/
|
||||
export default function transformData(fns, response) {
|
||||
const config = this || defaults;
|
||||
const context = response || config;
|
||||
const headers = AxiosHeaders.from(context.headers);
|
||||
let data = context.data;
|
||||
|
||||
utils.forEach(fns, function transform(fn) {
|
||||
data = fn.call(context, data, headers, status);
|
||||
data = fn.call(config, data, headers.normalize(), response ? response.status : undefined);
|
||||
});
|
||||
|
||||
headers.normalize();
|
||||
|
||||
return data;
|
||||
};
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user