Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactored adapters loader; #5277

Merged
merged 3 commits into from Nov 22, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
6 changes: 5 additions & 1 deletion index.d.ts
Expand Up @@ -277,6 +277,10 @@ export interface AxiosProgressEvent {

type Milliseconds = number;

type AxiosAdapterName = 'xhr' | 'http' | string;

type AxiosAdapterConfig = AxiosAdapter | AxiosAdapterName;

export interface AxiosRequestConfig<D = any> {
url?: string;
method?: Method | string;
Expand All @@ -290,7 +294,7 @@ export interface AxiosRequestConfig<D = any> {
timeout?: Milliseconds;
timeoutErrorMessage?: string;
withCredentials?: boolean;
adapter?: AxiosAdapter;
adapter?: AxiosAdapterConfig | AxiosAdapterConfig[];
auth?: AxiosBasicCredentials;
responseType?: ResponseType;
responseEncoding?: responseEncoding | string;
Expand Down
59 changes: 59 additions & 0 deletions lib/adapters/adapters.js
@@ -0,0 +1,59 @@
import utils from '../utils.js';
import httpAdapter from './http.js';
import xhrAdapter from './xhr.js';
import AxiosError from "../core/AxiosError.js";

const knownAdapters = {
http: httpAdapter,
xhr: xhrAdapter
}

utils.forEach(knownAdapters, (fn, value) => {
if(fn) {
try {
Object.defineProperty(fn, 'name', {value});
} catch (e) {
// eslint-disable-next-line no-empty
}
Object.defineProperty(fn, 'adapterName', {value});
}
});

export default {
getAdapter: (adapters) => {
adapters = utils.isArray(adapters) ? adapters : [adapters];

const {length} = adapters;
let nameOrAdapter;
let adapter;

for (let i = 0; i < length; i++) {
nameOrAdapter = adapters[i];
if((adapter = utils.isString(nameOrAdapter) ? knownAdapters[nameOrAdapter.toLowerCase()] : nameOrAdapter)) {
break;
}
}

if (!adapter) {
if (adapter === false) {
throw new AxiosError(
`Adapter ${nameOrAdapter} is not supported by the environment`,
'ERR_NOT_SUPPORT'
);
}

throw new Error(
utils.hasOwnProp(knownAdapters, nameOrAdapter) ?
`Adapter '${nameOrAdapter}' is not available in the build` :
`Unknown adapter '${nameOrAdapter}'`
);
}

if (!utils.isFunction(adapter)) {
throw new TypeError('adapter is not a function');
}

return adapter;
},
adapters: knownAdapters
}
4 changes: 3 additions & 1 deletion lib/adapters/http.js
Expand Up @@ -100,8 +100,10 @@ function setProxy(options, configProxy, location) {
};
}

const isHttpAdapterSupported = typeof process !== 'undefined' && utils.kindOf(process) === 'process';

/*eslint consistent-return:0*/
export default function httpAdapter(config) {
export default isHttpAdapterSupported && function httpAdapter(config) {
return new Promise(function dispatchHttpRequest(resolvePromise, rejectPromise) {
let data = config.data;
const responseType = config.responseType;
Expand Down
33 changes: 0 additions & 33 deletions lib/adapters/index.js

This file was deleted.

4 changes: 3 additions & 1 deletion lib/adapters/xhr.js
Expand Up @@ -43,7 +43,9 @@ function progressEventReducer(listener, isDownloadStream) {
};
}

export default function xhrAdapter(config) {
const isXHRAdapterSupported = typeof XMLHttpRequest !== 'undefined';

export default isXHRAdapterSupported && function (config) {
return new Promise(function dispatchXhrRequest(resolve, reject) {
let requestData = config.data;
const requestHeaders = AxiosHeaders.from(config.headers).normalize();
Expand Down
3 changes: 2 additions & 1 deletion lib/core/dispatchRequest.js
Expand Up @@ -5,6 +5,7 @@ import isCancel from '../cancel/isCancel.js';
import defaults from '../defaults/index.js';
import CanceledError from '../cancel/CanceledError.js';
import AxiosHeaders from '../core/AxiosHeaders.js';
import adapters from "../adapters/adapters.js";

/**
* Throws a `CanceledError` if cancellation has been requested.
Expand Down Expand Up @@ -45,7 +46,7 @@ export default function dispatchRequest(config) {
config.headers.setContentType('application/x-www-form-urlencoded', false);
}

const adapter = config.adapter || defaults.adapter;
const adapter = adapters.getAdapter(config.adapter || defaults.adapter);

return adapter(config).then(function onAdapterResolution(response) {
throwIfCancellationRequested(config);
Expand Down
21 changes: 1 addition & 20 deletions lib/defaults/index.js
Expand Up @@ -7,30 +7,11 @@ import toFormData from '../helpers/toFormData.js';
import toURLEncodedForm from '../helpers/toURLEncodedForm.js';
import platform from '../platform/index.js';
import formDataToJSON from '../helpers/formDataToJSON.js';
import adapters from '../adapters/index.js';

const DEFAULT_CONTENT_TYPE = {
'Content-Type': undefined
};

/**
* If the browser has an XMLHttpRequest object, use the XHR adapter, otherwise use the HTTP
* adapter
*
* @returns {Function}
*/
function getDefaultAdapter() {
let adapter;
if (typeof XMLHttpRequest !== 'undefined') {
// For browsers use XHR adapter
adapter = adapters.getAdapter('xhr');
} else if (typeof process !== 'undefined' && utils.kindOf(process) === 'process') {
// For node use HTTP adapter
adapter = adapters.getAdapter('http');
}
return adapter;
}

/**
* It takes a string, tries to parse it, and if it fails, it returns the stringified version
* of the input
Expand Down Expand Up @@ -60,7 +41,7 @@ const defaults = {

transitional: transitionalDefaults,

adapter: getDefaultAdapter(),
adapter: ['xhr', 'http'],

transformRequest: [function transformRequest(data, headers) {
const contentType = headers.getContentType() || '';
Expand Down
4 changes: 2 additions & 2 deletions package.json
Expand Up @@ -104,7 +104,7 @@
"url-search-params": "^0.10.0"
},
"browser": {
"./lib/adapters/http.js": "./lib/adapters/xhr.js",
"./lib/adapters/http.js": "./lib/helpers/null.js",
"./lib/platform/node/index.js": "./lib/platform/browser/index.js"
},
"jsdelivr": "dist/axios.min.js",
Expand Down Expand Up @@ -138,4 +138,4 @@
"Daniel Lopretto (https://github.com/timemachine3030)"
],
"sideEffects": false
}
}
14 changes: 14 additions & 0 deletions test/typescript/axios.ts
Expand Up @@ -497,3 +497,17 @@ axios.get('/user', {
console.log(e.rate);
}
});

// adapters

axios.get('/user', {
adapter: 'xhr'
});

axios.get('/user', {
adapter: 'http'
});

axios.get('/user', {
adapter: ['xhr', 'http']
});