dispatchRequest.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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.call(
  26. config,
  27. config.data,
  28. config.headers,
  29. config.transformRequest
  30. );
  31. // Flatten headers
  32. config.headers = utils.merge(
  33. config.headers.common || {},
  34. config.headers[config.method] || {},
  35. config.headers
  36. );
  37. utils.forEach(
  38. ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],
  39. function cleanHeaderConfig(method) {
  40. delete config.headers[method];
  41. }
  42. );
  43. var adapter = config.adapter || defaults.adapter;
  44. return adapter(config).then(function onAdapterResolution(response) {
  45. throwIfCancellationRequested(config);
  46. // Transform response data
  47. response.data = transformData.call(
  48. config,
  49. response.data,
  50. response.headers,
  51. config.transformResponse
  52. );
  53. return response;
  54. }, function onAdapterRejection(reason) {
  55. if (!isCancel(reason)) {
  56. throwIfCancellationRequested(config);
  57. // Transform response data
  58. if (reason && reason.response) {
  59. reason.response.data = transformData.call(
  60. config,
  61. reason.response.data,
  62. reason.response.headers,
  63. config.transformResponse
  64. );
  65. }
  66. }
  67. return Promise.reject(reason);
  68. });
  69. };