Blame view

apps/common/create-api-server.js 3 KB
lea guo authored
1 2 3
/* eslint-disable indent */
/* eslint-disable operator-linebreak */
TaoHuang authored
4 5 6 7 8 9 10 11 12 13
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;
};
lea guo authored
14
lea guo authored
15
// eslint-disable-next-line space-before-function-paren
shuaiguo authored
16
const request = async ({ url, method, reqParams = {}, context }) => {
TaoHuang authored
17
  const apiInfo = checkApiMap(url);
lea guo authored
18
  const { env, user = {} } = context;
TaoHuang authored
19 20 21 22

  if (!apiInfo) {
    return Promise.reject(new Error(`未找到对应的接口:${url}`));
  }
lea guo authored
23 24 25

  // 登陆:取session中用户信息
  // 非登录: 可以传参
TaoHuang authored
26
  if (!apiInfo.service) {
lea guo authored
27 28 29 30 31 32 33 34 35 36 37
    const { uid, sessionKey, appSessionType } = user;

    Object.assign(reqParams, { method: apiInfo.api });
    if (uid) {
      Object.assign(reqParams, {
        uid: {
          toString: () => {
            return user.uid;
          },
          sessionKey,
          appSessionType,
TaoHuang authored
38
        },
lea guo authored
39
      });
TaoHuang authored
40
    }
TaoHuang authored
41
  }
lea guo authored
42
TaoHuang authored
43 44 45 46 47
  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,
lea guo authored
48
    'User-Agent': 'yoho/nodejs',
TaoHuang authored
49 50 51 52 53 54
  };

  try {
    if (apiInfo.service) {
      return await serviceApi.get(`${apiInfo.api}${apiInfo.path}`, params, {
        cache: cache,
lea guo authored
55
        headers,
TaoHuang authored
56 57 58 59
      });
    } else if (apiInfo.ufo) {
      return await ufoAPI[method](`${apiInfo.path || ''}`, params, {
        cache: cache,
lea guo authored
60
        headers,
TaoHuang authored
61 62 63 64
      });
    } else {
      return await yohoApi[method](`${apiInfo.path || ''}`, params, {
        cache: cache,
lea guo authored
65
        headers,
TaoHuang authored
66 67 68 69 70
      });
    }
  } catch (error) {
    return Promise.reject({
      code: error.code || 500,
lea guo authored
71
      message: error.message || '服务器错误',
TaoHuang authored
72 73 74 75
    });
  }
};
lea guo authored
76 77 78 79
const resolve = ({ context, store, reqParams }) => {
  return res => {
    if (res) {
      const { code } = res;
TaoHuang authored
80
lea guo authored
81 82 83 84 85 86 87 88 89 90 91 92
      if (code === 500) {
        createReport(context, 'api')(
          Object.assign(
            {
              api: reqParams.method,
            },
            res,
          ),
        );
      } else if (code === 401) {
        store.commit('SET_NEED_LOGIN', { needLogin: true });
      }
TaoHuang authored
93
    }
lea guo authored
94
    return res;
TaoHuang authored
95 96 97
  };
};
lea guo authored
98
export const createApi = (context, store) => {
TaoHuang authored
99 100
  return {
    get(url, reqParams = {}) {
张文文 authored
101 102 103 104
      return request({
        url,
        method: 'get',
        reqParams,
lea guo authored
105 106
        context,
      })
lea guo authored
107
        .then(resolve({ context, store, reqParams }))
lea guo authored
108
        .catch(err => {
lea guo authored
109
          console.log('----create----api--server--get---', err);
lea guo authored
110
        });
TaoHuang authored
111 112
    },
    post(url, reqParams = {}) {
张文文 authored
113 114 115 116
      return request({
        url,
        method: 'post',
        reqParams,
lea guo authored
117 118
        context,
      })
lea guo authored
119
        .then(resolve({ context, store, reqParams }))
lea guo authored
120
        .catch(err => {
lea guo authored
121
          console.log('----create----api--server--post---', err);
lea guo authored
122 123
        });
    },
TaoHuang authored
124 125
  };
};