You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

79 lines
1.9 KiB

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