1 | import utils from '../utils.js';
|
---|
2 | import httpAdapter from './http.js';
|
---|
3 | import xhrAdapter from './xhr.js';
|
---|
4 | import fetchAdapter from './fetch.js';
|
---|
5 | import AxiosError from "../core/AxiosError.js";
|
---|
6 |
|
---|
7 | const knownAdapters = {
|
---|
8 | http: httpAdapter,
|
---|
9 | xhr: xhrAdapter,
|
---|
10 | fetch: fetchAdapter
|
---|
11 | }
|
---|
12 |
|
---|
13 | utils.forEach(knownAdapters, (fn, value) => {
|
---|
14 | if (fn) {
|
---|
15 | try {
|
---|
16 | Object.defineProperty(fn, 'name', {value});
|
---|
17 | } catch (e) {
|
---|
18 | // eslint-disable-next-line no-empty
|
---|
19 | }
|
---|
20 | Object.defineProperty(fn, 'adapterName', {value});
|
---|
21 | }
|
---|
22 | });
|
---|
23 |
|
---|
24 | const renderReason = (reason) => `- ${reason}`;
|
---|
25 |
|
---|
26 | const isResolvedHandle = (adapter) => utils.isFunction(adapter) || adapter === null || adapter === false;
|
---|
27 |
|
---|
28 | export default {
|
---|
29 | getAdapter: (adapters) => {
|
---|
30 | adapters = utils.isArray(adapters) ? adapters : [adapters];
|
---|
31 |
|
---|
32 | const {length} = adapters;
|
---|
33 | let nameOrAdapter;
|
---|
34 | let adapter;
|
---|
35 |
|
---|
36 | const rejectedReasons = {};
|
---|
37 |
|
---|
38 | for (let i = 0; i < length; i++) {
|
---|
39 | nameOrAdapter = adapters[i];
|
---|
40 | let id;
|
---|
41 |
|
---|
42 | adapter = nameOrAdapter;
|
---|
43 |
|
---|
44 | if (!isResolvedHandle(nameOrAdapter)) {
|
---|
45 | adapter = knownAdapters[(id = String(nameOrAdapter)).toLowerCase()];
|
---|
46 |
|
---|
47 | if (adapter === undefined) {
|
---|
48 | throw new AxiosError(`Unknown adapter '${id}'`);
|
---|
49 | }
|
---|
50 | }
|
---|
51 |
|
---|
52 | if (adapter) {
|
---|
53 | break;
|
---|
54 | }
|
---|
55 |
|
---|
56 | rejectedReasons[id || '#' + i] = adapter;
|
---|
57 | }
|
---|
58 |
|
---|
59 | if (!adapter) {
|
---|
60 |
|
---|
61 | const reasons = Object.entries(rejectedReasons)
|
---|
62 | .map(([id, state]) => `adapter ${id} ` +
|
---|
63 | (state === false ? 'is not supported by the environment' : 'is not available in the build')
|
---|
64 | );
|
---|
65 |
|
---|
66 | let s = length ?
|
---|
67 | (reasons.length > 1 ? 'since :\n' + reasons.map(renderReason).join('\n') : ' ' + renderReason(reasons[0])) :
|
---|
68 | 'as no adapter specified';
|
---|
69 |
|
---|
70 | throw new AxiosError(
|
---|
71 | `There is no suitable adapter to dispatch the request ` + s,
|
---|
72 | 'ERR_NOT_SUPPORT'
|
---|
73 | );
|
---|
74 | }
|
---|
75 |
|
---|
76 | return adapter;
|
---|
77 | },
|
---|
78 | adapters: knownAdapters
|
---|
79 | }
|
---|