create-api-server.js 2.52 KB
import checkParams from '../../utils/check-params';
import apiMaps from '../../config/api-map';
import createReport from 'report-error';

const yohoApi = global.yoho.API;
const ufoAPI = global.yoho.UfoAPI;
const serviceApi = global.yoho.ServiceAPI;


const checkApiMap = url => {
  return apiMaps[url] ? apiMaps[url] : void 0;
};
const request = async({url, method, reqParams = {}, context}) => {
  const apiInfo = checkApiMap(url);
  const {env, user} = context;

  if (!apiInfo) {
    return Promise.reject(new Error(`未找到对应的接口:${url}`));
  }
  if (!apiInfo.service) {
    reqParams.method = apiInfo.api;
  }
  if (apiInfo.auth) {
    if (user && user.uid) {
      reqParams.uid = {
        toString: () => {
          return user.uid;
        },
        sessionKey: user.sessionKey,
        appSessionType: user.appSessionType
      };
    }
  }

  const params = checkParams.getParams(reqParams, apiInfo, context);
  const cache = (method.toLowerCase() !== 'get' || apiInfo.auth) ? false : apiInfo.cache;
  const headers = {
    'X-YOHO-IP': env.clientIp,
    'X-Forwarded-For': env.clientIp,
    'User-Agent': 'yoho/nodejs'
  };

  try {
    if (apiInfo.service) {
      return await serviceApi.get(`${apiInfo.api}${apiInfo.path}`, params, {
        cache: cache,
        headers
      });
    } else if (apiInfo.ufo) {
      return await ufoAPI[method](`${apiInfo.path || ''}`, params, {
        cache: cache,
        headers
      });
    } else {
      return await yohoApi[method](`${apiInfo.path || ''}`, params, {
        cache: cache,
        headers
      });
    }
  } catch (error) {
    return Promise.reject({
      code: error.code || 500,
      message: error.message || '服务器错误'
    });
  }
};

const catchCode = (context, reqParams) => {
  return result => {
    if (result && result.code === 500) {
      createReport(context, 'api')(Object.assign({
        api: reqParams.method,
      }, result));
    }
    return result;
  };
};

const catchError = (context, store) => {
  return error => {
    if (error.code === 401) {
      store.commit('SET_NEED_LOGIN', {needLogin: true});
    }
    return Promise.resolve();
  };
};

export const createApi = (context, store) => {
  return {
    get(url, reqParams = {}) {
      return request({url, method: 'get', reqParams, context}).then(catchCode(context, reqParams)).catch(catchError(context, store));
    },
    post(url, reqParams = {}) {
      return request({url, method: 'post', reqParams, context}).then(catchCode(context, reqParams)).catch(catchError(context, store));
    }
  };
};