create-api-client.js 2.9 KB
import axios from 'axios';
import {get} from 'lodash';
import yoho from './yoho';
import sdk from 'common/sdk';
import qs from 'yoho-qs';

const protocol = location.protocol === 'yoho-protocol:' ? 'http:' : location.protocol;

axios.defaults.baseURL = `${protocol}//${location.host}/grass`;
axios.defaults.responseType = 'json';
axios.defaults.headers = {
  'X-Requested-With': 'XMLHttpRequest'
};

const errHandle = (error) => {
  let res = error.response;
  
  console.log(error);
  if (+res.status === 510) {
    if (get(res, 'data.data.refer')) {
      return window.location.href === get(res, 'data.data.refer');
    }
  }

  return Promise.reject({
    code: 500,
    message: '服务器开小差了~'
  });
};
const getUser = async(store) => {
  let {appUid, appSessionKey, appVersion, appClientType} = store.state.yoho.user;

  try {
    if (!appUid || !appSessionKey || !appVersion || !appClientType) {
      const {uid, session_key, app_version, client_type} = qs;

      if (uid && app_version && client_type) {
        appUid = +uid;
        appSessionKey = session_key;
        appVersion = app_version;
        appClientType = client_type;
        store.commit('SET_USER', {appUid, appSessionKey, appVersion, appClientType});

        if (!appUid || !appSessionKey) {
          sdk.getUser().then(user => { // 页面第一次进入时,app未登录情况下,有一定几率没有回调,所以异步更新
            if (user) {
              store.commit('SET_USER', {
                appUid: +user.uid,
                appSessionKey: user.sessionKey,
                appVersion: user.appVersion,
                appClientType: user.sessionType
              });
            }
          });
        }
      }
    }
  } catch (e) {
    store.dispatch('reportError', {error: e});
  }
  return {appUid, appSessionKey, appVersion, appClientType};
};

const request = async(options, store) => {
  if (yoho.isLocal && yoho.isApp) {
    options.headers = {
      'yoho-protocol': true
    };
    let {appUid, appSessionKey, appVersion, appClientType} = await getUser(store);

    if (appUid && appSessionKey && appVersion && appClientType) {
      options.headers['app-uid'] = appUid;
      options.headers['app-session-key'] = appSessionKey;
      options.headers['app-version'] = appVersion;
      options.headers['app-client-type'] = appClientType;
    }
  }
  return axios(options).then((res) => {
    if (res.data.code === 401) {
      store && store.commit('SET_NEED_LOGIN', {needLogin: true});
      return Promise.reject(res.data);
    }
    return res.data;
  }, errHandle);
};

export const createApi = (context, store) => {
  return {
    get(url, params, options) {
      return request(Object.assign({
        url,
        params,
        method: 'get',
      }, options), store);
    },
    post(url, data, options) {
      return request(Object.assign({
        url,
        data,
        method: 'post',
      }, options), store);
    }
  };
};