index.js 4.2 KB
Newer Older
dengxiaofeng's avatar
dengxiaofeng committed
1 2 3 4 5 6 7
/* eslint-disable  */
import axios from 'axios';
import assign from 'lodash/assign';
import toLower from 'lodash/toLower';
// import isArray from 'lodash/isArray';
// import isArrayLikeObject from 'lodash/isArrayLikeObject';
import isFunction from 'lodash/isFunction';
8 9 10 11
import extendConfig from './defaultConfig';
const globalConfig = {
  bizRedirectHandler: extendConfig.bizRedirectHandler
}
dengxiaofeng's avatar
dengxiaofeng committed
12 13 14 15 16 17 18 19
const globalConfigMatchers = [];
/* no-unused-vars */
const getMatchedConfig = requestConfig => {
  if (!globalConfigMatchers.length) {
    return null;
  }
  for (let i = 0, len = globalConfigMatchers.length; i < len; i += 1) {
    const [matcher, extendConfig] = globalConfigMatchers[i];
20
    // 匹配到第一个matcher就返回了, 存在后续配置不生效的情况
dengxiaofeng's avatar
dengxiaofeng committed
21
    if (matcher(requestConfig)) {
22
      console.log(`matched url: ${requestConfig.url}`)
dengxiaofeng's avatar
dengxiaofeng committed
23 24 25 26 27 28
      return extendConfig;
    }

    return null;
  }
};
张烨's avatar
张烨 committed
29
axios.defaults.withCredentials = true
30
axios.interceptors.request.use( function (request){
张烨's avatar
张烨 committed
31 32
  const token = localStorage.getItem('token')
  if(token){
张烨's avatar
张烨 committed
33
    request.headers.Authorization = 'Bearer ' + token
张烨's avatar
张烨 committed
34
  }
35 36 37 38 39 40
  return request
}, function (error) {
  // Any status codes that falls outside the range of 2xx cause this function to trigger
  // Do something with response error
  return Promise.reject(error);
})
41 42 43 44 45 46 47 48 49 50 51
axios.interceptors.response.use(function (response) {
  return response
}, (error) => {
  if (error.response) {
    switch (error.response.status) {
      case 401:
        globalConfig.bizRedirectHandler(error.response)
    }
  }
  return Promise.reject(error);
})
52

dengxiaofeng's avatar
dengxiaofeng committed
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 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
export const request = (config, ctx) => {
  const {
    url,
    method = 'GET',
    params,
    convertParams,
    converter,
    successMessage,
    ...restAxiosConfig
  } = config;

  let requestOptions = {
    ...restAxiosConfig,
    url,
    method,
  };

  const matchedConfig = getMatchedConfig(requestOptions);

  const curConf = assign({}, globalConfig, matchedConfig);

  const {
    bizRedirectHandler,
    bizDevErrorAdapter,
    bizErrorMessageAdapter,
    bizSuccessMessageAdapter,
    bizNotifyHandler,
    bizDataAdapter,
    bizParamsAdapter,
    bizRequestAdapter,
  } = curConf;

  let finalParams = params || {};

  if (bizParamsAdapter) {
    finalParams = bizParamsAdapter(finalParams);
  }

  const lMethod = toLower(method);

  if (lMethod === 'get' || lMethod === 'delete') {
    requestOptions.params = finalParams;
  } else {
    requestOptions.data = finalParams;
  }

  if (bizRequestAdapter) {
    requestOptions = bizRequestAdapter(requestOptions);
  }

张烨's avatar
张烨 committed
103
  return axios(requestOptions).then(raw => raw && raw.data)
dengxiaofeng's avatar
dengxiaofeng committed
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
    .then(
      res =>
        new Promise((resolve, reject) => {
          // 1. 重定向
          if (bizRedirectHandler) {
            bizRedirectHandler(res);
          }

          // 2. 开发级别信息转换
          const errorDesc = bizDevErrorAdapter ? bizDevErrorAdapter(res) : null;

          // 3. 用户级错误信息转换
          const errorMsg = bizErrorMessageAdapter
            ? bizErrorMessageAdapter(res)
            : null;

          // 4. 成功信息转换
          const successMsg = bizSuccessMessageAdapter
            ? bizSuccessMessageAdapter(res, successMessage)
            : null;

          // 5. 消息处理
          if (bizNotifyHandler) {
            bizNotifyHandler({
              errorDesc,
              errorMessage: errorMsg,
              successMessage: successMsg,
            });
          }

          // 生产环境只有 errorMsg 起作用
          if (errorDesc || errorMsg) {
            return reject(errorDesc || errorMsg);
          }

          // 6. 数据转换
          const data = bizDataAdapter ? bizDataAdapter(res) : res;

          resolve(data);
        }),
    );
};

request.defaults = axios.defaults;

149 150 151 152 153
request.use = (matcherOrConfig, extendConfig) => {
  if (isFunction(matcherOrConfig)) {
    // 如果是函数,则把第二个参数作为满足matcher函数的配置,
    // 换言之,只在matcher执行返回true时,才应用extendConfig
    globalConfigMatchers.push([matcherOrConfig, extendConfig]);
dengxiaofeng's avatar
dengxiaofeng committed
154
  } else {
155 156
    // 如果不是函数,则matcher就是一个配置对象,放到全局配置中
    globalConfig = assign({}, globalConfig, matcherOrConfig);
dengxiaofeng's avatar
dengxiaofeng committed
157 158
  }
};