dispatchRequest.js 2.1 KB

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