proxy.js 2.91 KB
/**
 * 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) => {
    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(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: '无权限访问的接口'
        });
    }
    let currentShop = _.find(req.user.shops, shop => shop.shopsId === _.parseInt(req.cookies._sign));

    if (currentShop) {
        let baseParams = {
            pid: req.session.LOGIN_UID,
            founder: req.session.LOGIN_UID,
            shopsId: currentShop.shopsId,
            shopId: currentShop.shopsId,
            shop: currentShop.shopsId,
            supplierId: currentShop.shopsBrands.length ? _.first(currentShop.shopsBrands).supplierId : 0,
            platform_id: config.platform,
            userId: req.session.LOGIN_UID
        };
        let reqParams = Object.assign({
            url: apiUrl,
            method: req.method.toLowerCase(),
            headers: {
                'x-shop-id': currentShop.shopsId,
                'x-user-id': req.session.LOGIN_UID,
                'Content-Type': 'application/json'
            }
        });
        let files = req.files && req.files.file || [];

        if (!_.isArray(files)) {
            files = [files];
        }

        if (req.method.toLowerCase() === 'get') {
            reqParams.qs = Object.assign(baseParams, req.query, req.body);
        } else if (files.length) {
            let reqFiles = {};

            _.each(files, file => {
                reqFiles[file.fieldName] = fs.createReadStream(file.path);
            });
            reqParams.formData = Object.assign(baseParams, req.query, req.body, reqFiles);
        } else {
            reqParams.body = JSON.stringify(Object.assign(baseParams, req.query, req.body));
        }

        return api.proxy(reqParams).on('error', error => {
            next({code: 500, message: error});
        }).pipe(res);
    }
    return res.status(401).json({
        code: 401,
        message: '无权限访问的店铺'
    });
};