proxy.js 1.21 KB
/**
 * 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);
    }

};