proxy.js 1.48 KB
/**
 * 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;

module.exports = (req, res, next) => {
    let api = new Api();

    api.setContext({
        req,
        res
    });
    let apiMap = req.path.split('/').filter(n => n).join('.');

    if (_.some(blacklist, n => n.toLowerCase() === apiMap.toLowerCase())) {
        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 shopsId = req.get('shopsId');
    let currentShop = _.find(userShops, shop => shop.id === shopsId);

    if (currentShop) {
        let params = Object.assign(req.query, req.body, {
            shopsId: currentShop.shopsId,
            userId: req.session.LOGIN_UID
        });

        return api[req.method.toLowerCase()](apiUrl, params).then(data => {
            res.json(data);
        }).catch(next);
    }
    return res.status(401).json({
        code: 401,
        message: '不存在的店铺'
    });
};