create-api-server.js
1.67 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
const api = global.yoho.API;
const service = global.yoho.ServiceAPI;
const checkParams = require('../../utils/check-params');
const apiMaps = require('../../config/api-map');
const NOT_FOUND_API_MAP = {
code: 400,
message: '未找到对应的接口'
};
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(NOT_FOUND_API_MAP);
}
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;
if (apiInfo.service) {
return await service.get(apiInfo.api, params, {
cache: cache,
code: 200,
headers: {
'X-YOHO-IP': env.clientIp,
'X-Forwarded-For': env.clientIp,
'User-Agent': 'yoho/nodejs'
}
});
} else {
return await api[method]('', params, {
code: 200,
cache: cache,
headers: {
'X-YOHO-IP': env.clientIp,
'X-Forwarded-For': env.clientIp,
'User-Agent': 'yoho/nodejs'
}
});
}
};
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});
}
};
};