demo.js 7.61 KB
Newer Older
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 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 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 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 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
import { notification } from 'antd';
import { getLocale, history } from 'umi';
import config from '@/config';
import { clearLoginStatus, getLocaleText } from '@/utils';
import HttpRequest from './kim-request';
import store from 'store';

// const codeMessage = {
//   200: getLocaleText('kim.system.request.200'),
//   201: getLocaleText('kim.system.request.201'),
//   202: getLocaleText('kim.system.request.202'),
//   204: getLocaleText('kim.system.request.204'),
//   400: getLocaleText('kim.system.request.400'),
//   401: getLocaleText('kim.system.request.401'),
//   403: getLocaleText('kim.system.request.403'),
//   404: getLocaleText('kim.system.request.404'),
//   406: getLocaleText('kim.system.request.406'),
//   410: getLocaleText('kim.system.request.410'),
//   422: getLocaleText('kim.system.request.422'),
//   500: getLocaleText('kim.system.request.500'),
//   502: getLocaleText('kim.system.request.502'),
//   503: getLocaleText('kim.system.request.503'),
//   504: getLocaleText('kim.system.request.504'),
// };

const {
  request: {
    baseUrl,
    apiPrefix,
    resCodeKey,
    resMessageKey,
    successCode,
    isThrowError = true,
    authCodes = ['error.system.authc'],
  },
} = config;

/**
 * 组装url
 * @param {url} url
 * @param {{}} more
 */
const merge = (url: string, more: any) => {
  if (more && more.apiPrefix && typeof more.apiPrefix === 'string') {
    return `${config.apiPrefix}${url}`;
  }
  if (apiPrefix && typeof apiPrefix === 'string') {
    return `${config.apiPrefix}${url}`;
  }
  return url;
};

const headers = () => ({
  Authorization: store.get('token'),
  'X-Access-Lang': getLocale().replace(/-/, '_'),
});

const axios = new HttpRequest({
  baseUrl,
  headers: headers || {},
});

/**
 * 正常返回结果处理
 * @param {返回请求数据} response
 * @param {配置项} more
 */
const handleResponse = (response) => {
  const { data } = response;
  console.log('response', response);
  //
  if (`${data[resCodeKey]}` !== `${successCode}`) {
    if (isThrowError) {
      const errorMessage =
        data[resMessageKey] || getLocaleText('kim.system.request.default.message');
      let error = new Error();
      error = { ...error, ...data };
      error.code = data[resCodeKey];
      error.message = errorMessage;
      return Promise.reject(error);
    }
  }
  // success
  return data;
};

const handleError = (error, more) => {
  const codeMessage = {
    200: getLocaleText('kim.system.request.200'),
    201: getLocaleText('kim.system.request.201'),
    202: getLocaleText('kim.system.request.202'),
    204: getLocaleText('kim.system.request.204'),
    400: getLocaleText('kim.system.request.400'),
    401: getLocaleText('kim.system.request.401'),
    403: getLocaleText('kim.system.request.403'),
    404: getLocaleText('kim.system.request.404'),
    406: getLocaleText('kim.system.request.406'),
    410: getLocaleText('kim.system.request.410'),
    422: getLocaleText('kim.system.request.422'),
    500: getLocaleText('kim.system.request.500'),
    502: getLocaleText('kim.system.request.502'),
    503: getLocaleText('kim.system.request.503'),
    504: getLocaleText('kim.system.request.504'),
  };
  const { response } = error;
  const options = { isThrowError, ...more };
  // status
  if (response && response.status) {
    const errorText = codeMessage[response.status] || response.statusText;
    const {
      status,
      config: { url },
    } = response;
    notification.error({
      message: `${getLocaleText('kim.system.request.dialog.title')} ${status}`,
      description: `${url}${errorText}`,
    });
    // 跳转到404页面
    if (status >= 404 && status < 422) {
      history.push('/exception/404');
    }
    if (status <= 504 && status >= 500) {
      history.push('/exception/500');
    }
    // 跳转到登录页面 可能原因:token 失效
    if (status === 403 && status === 401) {
      clearLoginStatus();
      history.push('/user/login');
    }
  } else {
    // code
    const { code, message } = error;

    notification.error({
      key: `notification_${code ? message : code}`,
      message: getLocaleText('kim.system.request.dialog.title'),
      description: message,
    });
    // 跳转到登录页面 可能原因:token 失效
    if (authCodes && authCodes.includes(code)) {
      // 清空相关信息
      clearLoginStatus();
      history.push('/user/login');
    }
  }

  if (options.isThrowError) {
    throw error;
  } else {
    return error;
  }
};

export default function request(url, options = {}, more = {}, handle = false) {
  let newOptions = options;
  newOptions.url = url;
  if (more.headers) {
    newOptions = { ...options, headers: more.headers };
  }
  if (handle) {
    return axios.request(newOptions);
  }
  return axios
    .request(newOptions)
    .then((response) => handleResponse(response, more))
    .catch((error) => handleError(error, more));
}

/**
 * get请求
 * @param url
 * @param data
 * @param more
 * @returns {AxiosPromise<any>|Promise<Promise<never> | 返回请求数据.data | *>}
 */
const get = (url, data, more = {}) => {
  if (data?.current && !data?.pageNum) {
    // eslint-disable-next-line no-param-reassign
    data.pageNum = data.current;
  }
  return request(
    `${merge(url, more)}`,
    {
      method: 'get', // default
      params: data,
    },
    more,
  );
};

/**
 * post请求
 * @param url
 * @param data
 * @param more
 * @returns {AxiosPromise<any>|Promise<Promise<never> | 返回请求数据.data | *>}
 */
const post = (url, data, more = {}) =>
  request(
    `${merge(url, more)}`,
    {
      method: 'post', // default
      data,
    },
    more,
  );

/**
 * put请求
 * @param url
 * @param data
 * @param more
 * @returns {AxiosPromise<any>|Promise<Promise<never> | 返回请求数据.data | *>}
 */
const put = (url, data, more = {}) =>
  request(
    `${merge(url, more)}`,
    {
      method: 'put', // default
      data,
    },
    more,
  );

/**
 * delete请求
 * @param url
 * @param data
 * @param more
 * @returns {AxiosPromise<any>|Promise<Promise<never> | 返回请求数据.data | *>}
 */
const del = (url, data, more = {}) =>
  request(
    `${merge(url, more)}`,
    {
      method: 'delete', // default
      data,
    },
    more,
  );

/**
 * patch请求
 * @param url
 * @param data
 * @param more
 * @returns {AxiosPromise<any>|Promise<Promise<never> | 返回请求数据.data | *>}
 */
const patch = (url, data, more = {}) =>
  request(
    `${merge(url, more)}`,
    {
      method: 'patch', // default
      data,

      ...more,
    },
    more,
  );

const downloadFile = (url, data, more = {}) => {
  console.log('xiazai');
  return request(
    `${merge(url, more)}`,
    {
      method: 'get', // default
      params: data,
      responseType: 'blob',
    },
    more,
    true,
  ).then((response) => {
    return new Blob([response.data]);
  });
};

const formDataUpload = (url, options, more = {}) => {
  const formData = new FormData();
  if (options) {
    Object.keys(options).forEach((key) => {
      formData.append(key, options[key]);
    });
  }
  return post(`${merge(url, more)}`, formData, {
    headers: {
      'Content-Type': 'multipart/form-data',
      Authorization: store.get('token'),
    },
    ...more,
  }).then((res) => {
    const { code } = res;
    if (code === 'sys.success' && typeof options.onSuccess) {
      return options.onSuccess(res);
    }
    return res;
  });
};

/**
 * 上传文件
 * @param {url} url
 * @param {data} data
 * @param {type} type
 * @param {more} more
 */
const uploadFile = (url, data, type = 'formData', more = {}) => {
  if (type === 'formData') {
    return formDataUpload(url, data, more);
  }
  return null;
};

export { request, get, post, put, del, patch, uploadFile, downloadFile };