proxy.js
1.21 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
/**
* controller 入口
* @author: feng.chen<feng.chen@yoho.cn>
* @date: 2017/04/13
*/
const Api = require('../common/api');
const allowdUrls = global.yoho.apiDomain;
const _ = require('lodash');
const Fn = require('lodash/fp');
const logger = global.yoho.logger;
function _matchUrl(path, api) {
return api.path.toLowerCase() === path.toLowerCase();
}
function allowed(path) {
return _.flow(_.toPairs, Fn.find((api) => {
return _matchUrl(path, api[1])
}))(allowdUrls.shop);
}
module.exports = (req, res, next) => {
let api = new Api();
api.setContext({
req,
res
});
let allowApi = allowed(req.path);
if (!allowApi) {
logger.warn(`proxy ${req.method} fail`, `${req.path} can't find proxy url`);
return next();
}
logger.info(`proxy ${req.method} successful ok`, `[${req.path}] => [${allowApi[1].url}]`);
if (req.method.toLowerCase() === 'get') {
return api.get(allowApi[1].url, req.query).then(data => {
res.json(data);
}).catch(next);
}
if (req.method.toLowerCase() === 'post') {
return api.post(allowApi[1].url, req.body).then(data => {
res.json(data);
}).catch(next);
}
};