proxy.js
3.03 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
/**
* controller 入口
* @author: feng.chen<feng.chen@yoho.cn>
* @date: 2017/04/13
*/
const Api = require('../common/api');
const _ = require('lodash');
const fs = require('fs');
const blacklist = require('../common/api-blacklist');
const config = global.yoho.config;
const logger = global.yoho.logger;
const apiReg = /^\/Api/;
module.exports = (req, res, next) => {
const api = new Api();
api.setContext({
req,
res,
});
if (!apiReg.test(req.path)) {
return next({
code: 404,
});
}
const 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: '无权限访问的接口',
});
}
const apiUrl = _.get(config.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: '无权限访问的接口',
});
}
const currentShop = _.find(req.user.shops, shop => shop.shopsId === _.parseInt(req.cookies._sign));
if (currentShop) {
const baseParams = {
pid: req.user.uid,
founder: req.user.uid,
shopsId: currentShop.shopsId,
shopId: currentShop.shopsId,
shop: currentShop.shopsId,
supplierId: currentShop.shopsBrands.length
? req.user.supplier_id
? req.user.supplier_id
: _.first(currentShop.shopsBrands).supplierId
: 0,
platform_id: config.platform,
userId: req.user.uid,
};
const reqOptions = {
url: apiUrl,
method: req.method.toLowerCase(),
headers: {
'x-shop-id': currentShop.shopsId,
'x-user-id': req.user.uid,
'Content-Type': 'application/json',
},
};
if (req.body.timeout) {
reqOptions.timeout = req.body.timeout;
}
const reqParams = { ...req.query, ...req.body };
let files = (req.files && req.files.file) || [];
if (!_.isArray(files)) {
files = [files];
}
if (reqParams.platform_id) {
delete baseParams.platform_id;
}
// filter default params
if (apiMap.startsWith('erp.franchise')) {
// 删除专营店的供应商
delete baseParams.supplierId;
}
if (req.method.toLowerCase() === 'get') {
reqOptions.qs = Object.assign(reqParams, baseParams);
} else if (files.length) {
const reqFiles = {};
_.each(files, file => {
reqFiles[file.fieldName] = fs.createReadStream(file.path);
});
reqOptions.formData = Object.assign(reqParams, baseParams, reqFiles);
} else {
reqOptions.body = JSON.stringify(Object.assign(reqParams, baseParams));
}
return api
.proxy(reqOptions)
.on('error', error => {
next({ code: 500, message: error });
})
.pipe(res);
}
return res.status(401).json({
code: 401,
message: '无权限访问的店铺',
});
};