predata.js 1.65 KB
import Vue from 'vue';

function getDataKey(method, params) {
  return `${method}${Object.keys(params)
    .filter(key => typeof params[key] !== 'undefined')
    .sort()
    .map(key => `${key}=${params[key]}`).join('&')}`;
}


function getPredata(key) {
  return global.predatas.find(item => item.key === key);
}

function fetch($api) {
  return function(url, params, options) {
    if (process.env.VUE_ENV === 'server') {
      return $api.get(url, params, options);
    }
    let ispredata = {
      val: false
    };
    const dataKey = `predata_${getDataKey(url, params)}`;
    const precall = (resolve) => {
      return data => {
        ispredata.val = true;
        resolve(data);
      };
    };
    const preData = getPredata(dataKey);

    if (preData) {
      return preData.value;
    }
    return new Promise(async(resolve, reject) => {
      const call = precall(resolve);

      Vue.$bus.$on(dataKey, call);

      // await new Promise(r => {
      //   setTimeout(() => {
      //     r();
      //   }, 3000);
      // });
      return $api.get(url, params, options).then(data => {
        Vue.$bus.$off(dataKey, call);
        if (!ispredata.val) {
          resolve(data);
        }
      }).catch(reject);
    });
  };
}


function init() {
  if (!global.predatas) {
    global.predatas = [];
  }
  const pushOrigin = global.predatas.push.bind(global.predatas);

  global.predatas.push = function(item) {
    if (item.key) {
      Vue.$bus.$emit(item.key, item.value);
    }
    return pushOrigin(item);
  };
}

export default ($api) => {
  if (process.env.VUE_ENV !== 'server') {
    init();
  }
  return {
    fetch: fetch($api),
    getpre: getPredata
  };
};