create-api.js 1.43 KB
import axios from 'axios';
import iView from 'iview';
import bus from 'utils/bus';

const baseParams = {
  app_version: '6.6.0',
  business_line: 'yohobuy',
  client_type: 'miniapp',
  debug: 'XYZ',
  _sncp: 'NGJjYjhkNmwwZGM0OTk0YmQyMTMwZjlmoTZmzjY4cjN'
};

class CreateApi {
  constructor({baseURL}) {
    this.$api = axios.create({
      baseURL
    });
    this.$api.defaults.headers = {
      'X-Requested-With': 'XMLHttpRequest'
    };
  }
  async get(url, params, options) {
    return await this._request(Object.assign({
      url,
      params: Object.assign({}, params, baseParams),
      method: 'get'
    }), options);
  }
  async post(url, data, options) {
    return await this._request(Object.assign({
      url,
      data: Object.assign({}, data, baseParams),
      method: 'post'
    }, options));
  }
  _errHandle({response}) {
    let error = {
      code: 500,
      message: response.data && response.data.message || '接口异常'
    };

    if (response.status === 401) {
      const {data} = response;

      if (data) {
        error = data;
        if (data.code !== 999) {
          bus.$emit('logout');
        }
      }
    }
    return Promise.reject(error);
  }
  async _request(options) {
    try {
      return await this.$api(options).then(res => res.data, this._errHandle);
    } catch ({message}) {
      iView.Message.destroy();
      iView.Message.warning(message);
      return void 0;
    }
  }
}


export default CreateApi;