dispatchRequest.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. 'use strict';
  2. var utils = require('./../utils');
  3. var transformData = require('./transformData');
  4. var isCancel = require('../cancel/isCancel');
  5. var defaults = require('../defaults');
  6. var isAbsoluteURL = require('./../helpers/isAbsoluteURL');
  7. var combineURLs = require('./../helpers/combineURLs');
  8. /**
  9. * Throws a `Cancel` if cancellation has been requested.
  10. */
  11. function throwIfCancellationRequested(config) {
  12. if (config.cancelToken) {
  13. config.cancelToken.throwIfRequested();
  14. }
  15. }
  16. /**
  17. * Dispatch a request to the server using the configured adapter.
  18. *
  19. * @param {object} config The config that is to be used for the request
  20. * @returns {Promise} The Promise to be fulfilled
  21. */
  22. module.exports = function dispatchRequest(config) {
  23. throwIfCancellationRequested(config);
  24. // Support baseURL config
  25. if (config.baseURL && !isAbsoluteURL(config.url)) {
  26. config.url = combineURLs(config.baseURL, config.url);
  27. }
  28. // Ensure headers exist
  29. config.headers = config.headers || {};
  30. // Transform request data
  31. config.data = transformData(
  32. config.data,
  33. config.headers,
  34. config.transformRequest
  35. );
  36. // Flatten headers
  37. config.headers = utils.merge(
  38. config.headers.common || {},
  39. config.headers[config.method] || {},
  40. config.headers || {}
  41. );
  42. utils.forEach(
  43. ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],
  44. function cleanHeaderConfig(method) {
  45. delete config.headers[method];
  46. }
  47. );
  48. var adapter = config.adapter || defaults.adapter;
  49. return adapter(config).then(function onAdapterResolution(response) {
  50. throwIfCancellationRequested(config);
  51. // Transform response data
  52. response.data = transformData(
  53. response.data,
  54. response.headers,
  55. config.transformResponse
  56. );
  57. return response;
  58. }, function onAdapterRejection(reason) {
  59. if (!isCancel(reason)) {
  60. throwIfCancellationRequested(config);
  61. // Transform response data
  62. if (reason && reason.response) {
  63. reason.response.data = transformData(
  64. reason.response.data,
  65. reason.response.headers,
  66. config.transformResponse
  67. );
  68. }
  69. }
  70. return Promise.reject(reason);
  71. });
  72. };