request.js 2.2 KB
Newer Older
duanledexianxianxian's avatar
duanledexianxianxian committed
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
import { notification } from 'antd';
import HttpRequest from './kim-request';
import config from '@/config';

const { baseUrl, apiPrefix, headers } = config;

/**
 * 异常倄理程序
 */
const errorHandler = error => {
  const { response } = error;
  if (response && response.status) {
    const errorText = response.statusText;
    const { status, url, code } = response;
    notification.error({
      key: `notification_${code}`,
      message: `请求错误 ${status}: ${url}`,
      description: errorText,
    });
  }
};

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

const mergeApi = (url, more) => {
  if (more && more.apiPrefix && typeof more.apiPrefix === 'string') {
    return `${config.apiPrefix}${url}`;
  }
  if (apiPrefix && typeof apiPrefix === 'string') {
    return `${config.apiPrefix}${url}`;
  }
  return url;
};

const get = (url, data, more = {}) =>
  axios.request({
    method: 'get', // default
    url: `${mergeApi(url, more)}`,
    params: data,
    ...more,
  });

const post = (url, data, more = {}) =>
  axios.request({
    method: 'post', // default
    url: `${mergeApi(url, more)}`,
    data,
    ...more,
  });

const put = (url, data, more = {}) =>
  axios.request({
    method: 'put', // default
    url: `${mergeApi(url, more)}`,
    data,
    ...more,
  });

const del = (url, data, more = {}) =>
  axios.request({
    method: 'delete', // default
    url: `${mergeApi(url, more)}`,
    data,
    ...more,
  });

const patch = (url, data, more = {}) =>
  axios.request({
    method: 'patch', // default
    url: `${mergeApi(url, more)}`,
    data,
    ...more,
  });

const formDataUpload = (url, data, more = {}) => {
  const formData = new FormData();
  if (data) {
    Object.keys(data).forEach(key => {
      formData.append(key, data[key]);
    });
  }
  axios.request({
    method: 'post', // default
    url: `${mergeApi(url, more)}`,
    data: formData,
    headers: {
      'Content-Type': 'multipart/form-data',
    },
    ...more,
  });
};

const uploadFile = (url, data, type = 'formData', more = {}) => {
  if (type === 'formData') {
    formDataUpload(url, data, more);
  }
};

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