All files / lib/core dispatchRequest.js

95.65% Statements 22/23
68.75% Branches 11/16
100% Functions 5/5
95.65% Lines 22/23

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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