api.js 1.62 KB
import util from '@/libs/util';
import iView from 'iview';
import qs from 'qs';

class Api {
  constructor() {
  }

  _get(url, data = {}, options = {}) {
    console.log('data')
    console.log(data)
    console.log('options')
    console.log(options)
    let params = this._2params(data);
    if (!PRODUCTION) { //eslint-disable-line
      params.debug = 'XYZ';
    }
    console.log("url:"+url)

    return util.ajax.get(url, Object.assign({params}, options)).then(result => result.data).catch(this.catch);
  }

  _post(url, data = {}, json = false, options = {}) {
    let params = this._2params(data);

    if (!PRODUCTION) { //eslint-disable-line
      url += (url.indexOf('?') >= 0 ? '&' : '?') + 'debug=XYZ';
    }
    if (!json) {
      params = qs.stringify(params);
    }

    return util.ajax.post(url, params, options).then(result => {
      return result.data;
    }).catch(this.catch);
  }

  _postForm(url, data, options = {}) {
    if (!PRODUCTION) { //eslint-disable-line
      url += (url.indexOf('?') >= 0 ? '&' : '?') + 'debug=XYZ';
    }
    return util.ajax.post(url, data, options).then(result => {
      return result.data;
    }).catch(this.catch);
  }

  catch({message}) {
    iView.Message.destroy();
    iView.Message.warning(message || '接口错误');
    return Promise.resolve({});
  }

  _2params(data) {
    if (Array.isArray(data)) {
      return data;
    }

    const params = {};
    Object.keys(data).forEach(k => {
      if (k === 'investName') {
        params[k] = data[k] || '';
      } else if (data[k] || data[k] === 0) {

        params[k] = data[k];
      }
    });
    return params;
  }
}

export default Api;