create-api-server.js 1.78 KB
const yohoApi = global.yoho.API;
const ufoAPI = global.yoho.UfoAPI;
const serviceApi = global.yoho.ServiceAPI;
const checkParams = require('../../utils/check-params');
const apiMaps = require('../../config/api-map');

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) {
    Object.assign(reqParams, {
      uid: (user && user.uid) ? {
        toString: () => {
          return user.uid;
        },
        sessionKey: user.sessionKey,
        appSessionType: user.appSessionType
      } : 1,
      method: apiInfo.api,
    });
  }

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

  if (apiInfo.service) {
    return await serviceApi.get(`${apiInfo.api}${apiInfo.path}`, params, {
      cache: cache,
      code: 200,
      headers
    }).catch(console.log);
  } else if (apiInfo.ufo) {
    return await ufoAPI[method](`${apiInfo.path || ''}`, params, {
      cache: cache,
      code: 200,
      headers
    });
  } else {
    return await yohoApi[method](`${apiInfo.path || ''}`, params, {
      code: 200,
      cache: cache,
      headers
    }).catch(console.log);
  }
};

export const createApi = context => {
  return {
    get(url, reqParams) {
      return request({url, method: 'get', reqParams, context});
    },
    post(url, reqParams) {
      return request({url, method: 'post', reqParams, context});
    }
  };
};