proxy.js
2.13 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
/**
* controller 入口
* @author: feng.chen<feng.chen@yoho.cn>
* @date: 2017/04/13
*/
const Api = require('../common/api');
const _ = require('lodash');
const blacklist = require('../common/api-blacklist');
const apiDomain = global.yoho.apiDomain;
const logger = global.yoho.logger;
const apiReg = /^\/Api/;
module.exports = (req, res, next) => {
let api = new Api();
api.setContext({
req,
res
});
if (!apiReg.test(req.path)) {
return next({
code: 404
});
}
let apiMap = req.path.replace(apiReg, '').split('/').filter(n => n).join('.');
if (_.some(blacklist, n => n.toLowerCase() === apiMap.toLowerCase())) {
logger.error(`proxy [${req.method}] fail`, `${req.path} can't blacklist`);
return res.status(401).json({
code: 401,
message: '无权限访问的接口'
});
}
let apiUrl = _.get(apiDomain, apiMap);
if (!apiUrl) {
logger.error(`proxy [${req.method}] fail`, `${req.path} can't find proxy url`);
return res.status(400).json({
code: 400,
message: '无权限访问的接口'
});
}
let userShops = req.user.shops;
let currentShop = _.find(userShops, shop => shop.id === req.cookies._sign);
if (currentShop) {
let channel = apiMap.split('.')[0];
let baseParams;
if (channel === 'erp') {
baseParams = {
pid: req.session.LOGIN_UID,
shopId: currentShop.shopsId,
platform_id: 2
};
} else if (channel === 'platform') {
baseParams = {
shopsId: currentShop.shopsId,
shopId: currentShop.shopsId,
userId: req.session.LOGIN_UID
};
}
let params = Object.assign(req.query, req.body, baseParams);
return api.proxy(apiUrl, params, {
method: req.method.toLowerCase()
}).on('error', error => {
next({code: 500, message: error});
}).pipe(res);
}
return res.status(401).json({
code: 401,
message: '不存在的店铺'
});
};