index.js 4.9 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
import extendConfig from './defaultConfig';
const globalConfig = {
邓超's avatar
邓超 committed
10 11
  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)) {
邓超's avatar
邓超 committed
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 30 31 32 33 34 35 36
axios.defaults.withCredentials = true;
axios.interceptors.request.use(
  function(request) {
    const token = localStorage.getItem('token');
    const pandaPublish = localStorage.getItem('panda-publish');
    const getWay = '/PandaCore/GateWay';
    if (token) {
      request.headers.Authorization = 'Bearer ' + token;
37
    }
邓超's avatar
邓超 committed
38 39 40 41 42 43
    if (pandaPublish) {
      console.log(request.url, 'request.url');
      if (
        request.url != '/PandaOMS/OMS/OMSLogin' &&
        request.url != '/Publish/OMS/FileCenter/SaveMobileApk' &&
        request.url != '/PandaOMS/OMS/HostManager/GetGateWay' &&
44
        !request.url.includes('/PandaCore/GateWay/')
邓超's avatar
邓超 committed
45 46 47
      )
        request.url = getWay + request.url;
    }
48 49 50 51 52 53
    if (/get/i.test(request.method)) {
      //判断get请求
      request.params = request.params || {};
      request.params.v = Date.parse(new Date()) / 1000; //添加时间戳
    }

邓超's avatar
邓超 committed
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
    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);
  },
);
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);
  },
);
76

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

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

          // 3. 用户级错误信息转换
邓超's avatar
邓超 committed
141
          const errorMsg = bizErrorMessageAdapter ? bizErrorMessageAdapter(res) : null;
dengxiaofeng's avatar
dengxiaofeng committed
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171

          // 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;

172 173 174 175 176
request.use = (matcherOrConfig, extendConfig) => {
  if (isFunction(matcherOrConfig)) {
    // 如果是函数,则把第二个参数作为满足matcher函数的配置,
    // 换言之,只在matcher执行返回true时,才应用extendConfig
    globalConfigMatchers.push([matcherOrConfig, extendConfig]);
dengxiaofeng's avatar
dengxiaofeng committed
177
  } else {
178 179
    // 如果不是函数,则matcher就是一个配置对象,放到全局配置中
    globalConfig = assign({}, globalConfig, matcherOrConfig);
dengxiaofeng's avatar
dengxiaofeng committed
180 181
  }
};