adapters.js 1.9 KB

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