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

class Api {
  constructor() {
  }

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

    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);
  }

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

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

export default Api;