"use strict";

var _interopRequireDefault = require("@babel/runtime-corejs2/helpers/interopRequireDefault");

exports.__esModule = true;
exports.default = void 0;

var _axios = _interopRequireDefault(require("axios"));

var _merge = _interopRequireDefault(require("lodash/merge"));

var _constant = require("../_utils/constant");

/*
 * @Author: lijianzhang
 * @Date: 2018-11-02 14:12:15
 * @Last Modified by: lijianzhang
 * @Last Modified time: 2019-02-22 14:20:19
 */
var CancelToken = _axios.default.CancelToken;
var baseURL = _constant.REQUEST_RUL;

var request = _axios.default.create({
  baseURL,
  withCredentials: true,
  timeout: 30 * 1000 // 超时限制 30秒

});

var STATUS_CODES = {
  '401': 'User not authenticated'
};
request.interceptors.response.use(function (res) {
  if (res.headers['x-pagination']) {
    try {
      res.pagination = JSON.parse(res.headers['x-pagination']);
    } catch (error) {
      throw new Error('无效的 pagination 数据');
    }
  }

  return res;
}, function (err) {
  if (err.message === 'Network Error') throw new Error('网络加载失败，请检查您的网络设置');
  if (!err.response) throw err;

  if (STATUS_CODES[err.response.status]) {
    throw new Error(STATUS_CODES[err.response.status]);
  } else {
    throw new Error(err.response.data.message || err.response.data);
  }
});
var post = request.post.bind(request);

request.post = function (url, data, config) {
  if (data === void 0) {
    data = {};
  }

  if (config === void 0) {
    config = {};
  }

  var cancel;
  var cancelToken = new CancelToken(function executor(c) {
    // An executor function receives a cancel function as a parameter
    cancel = c;
  });
  var promise = post(url, data, (0, _merge.default)(config, {
    cancelToken
  }));
  promise.cancel = cancel;
  return promise;
};

request.setBaseURL = function (url) {
  request.defaults.baseURL = url;
};

var _default = request;
exports.default = _default;