create-api-server.js
3.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
/* eslint-disable indent */
/* eslint-disable operator-linebreak */
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;
};
// eslint-disable-next-line space-before-function-paren
const request = async ({ url, method, reqParams = {}, context }) => {
const apiInfo = checkApiMap(url);
const { env, user = {} } = context;
if (!apiInfo) {
return Promise.reject(new Error(`未找到对应的接口:${url}`));
}
// 登陆:取session中用户信息
// 非登录: 可以传参
if (!apiInfo.service) {
const { uid, sessionKey, appSessionType } = user;
Object.assign(reqParams, { method: apiInfo.api });
if (uid) {
Object.assign(reqParams, {
uid: {
toString: () => {
return user.uid;
},
sessionKey,
appSessionType,
},
});
}
}
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',
};
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 resolve = ({ context, store, reqParams }) => {
return res => {
if (res) {
const { code } = res;
if (code === 500) {
createReport(context, 'api')(
Object.assign(
{
api: reqParams.method,
},
res,
),
);
} else if (code === 401) {
store.commit('SET_NEED_LOGIN', { needLogin: true });
}
}
return res;
};
};
export const createApi = (context, store) => {
return {
get(url, reqParams = {}) {
return request({
url,
method: 'get',
reqParams,
context,
})
.then(resolve({ context, store, reqParams }))
.catch(err => {
console.log('----create----api--server--get---', err);
return err;
});
},
post(url, reqParams = {}) {
return request({
url,
method: 'post',
reqParams,
context,
})
.then(resolve({ context, store, reqParams }))
.catch(err => {
console.log('----create----api--server--post---', err);
return err;
});
},
};
};