grayroute.js 3.48 KB
/**
 * 灰度界面代理中间件
 * @author h1bomb
 */
var request = require('request');

var config = require('../config/gray');

/**
 * 灰度界面配置
 * @param  {Object} proxyRoute 
 * @return {Function}  返中间件
 */
module.exports = function(proxyRoute) {
  /**
   *  灰度界面中间件
   * @param  {Object} req  请求对象
   * @param  {Object} res  响应对象
   * @param  {Function} next 执行下个中间件
   * @return {void}       无返回
   */
   return function(req, ress, next) {
    //日志记录器
    var logger = req.app.logger;
    //方法名称
    var method = req.method;

    //访问路由路径
    var path = req.route?req.route.path:'';

    //路由的hash key
    var key = proxyRoute.genKey(method,path);
    
    //登出,清掉cookie
    if(path === '/logout') {
       req.session.gray = null;
       next();
       return;
    }

    //如果新系统路由没有,代理到老平台
    if(!proxyRoute.interfacesConfig[key]) {
      
      //老系统调用地址
      var callUrl = config.url + req.originalUrl;
      //gray 透传cookie
      var options = {
        method:method,
        url:callUrl,
        timeout:config.timeout,
        headers: {
          'Cookie':req.session.gray
        }
      }

      if(!req.session.gray) {
        logger.log('warn','grayroute: cookie missed',req.session.user);
      }

      //如果是Ajax请求加上 Ajax头
      if(req.headers['x-requested-with']) {
        options.headers['X-Requested-With'] = 'XMLHttpRequest';
      }

      if(req.headers['referer']) {
        options.headers['Referer'] = req.headers['referer'];
      }
      
      //如果是POST,设置form表单的传参
      if(method === "POST") {
        options.form = req.body;
      }
      logger.log('info','grayroute: request options: %j',options,{});
      //发起代理请求
      request(options,callback);

      //代理回调
      function callback(err,res,body) {
        if(err) {
          logger.log('error','grayroute: request error:',err);
          ress.status(500).send('');
        } else if(res&&res.statusCode === 200) {
          setGrayCookie(req,res);
          var ContentType = res.caseless.get('Content-Type');
          ress.append('Content-Type',ContentType);
          ress.send(body);
        
        } else if(res&&res.statusCode === 302) {
          var curCookie = setGrayCookie(req,res);
          if(!curCookie||curCookie.length<1) {
            res.session.user = null;
          }
          //跳转
          ress.redirect(res.caseless.get('location'));
        } else if(res){
          ress.status(res.statusCode).send(body);
        } else {
          ress.status(500).send('500 ERROR!');
        }
      }
    } else {

      //当不是老系统的URL,需要访问老系统保持session
      request({
        method:'GET',
        url: config.url + config.sessionKeep,
        headers: {
          'Cookie':req.session.gray
        }
      },function(err,res,body){
        var code = res?res.statusCode:'no response';
        logger.log('info','grayroute: session keep status:'+code);
      });

      next();
    }
  }
 }
  
  /**
   * 灰度cookie设置
   * @param {Object} req express request
   * @param {Object} res request的响应
   */
 function setGrayCookie(req,res) {
    //cookie透传到老系统
    var cookie = res.caseless.get('set-cookie');
    //如果没有设置到session
    if(cookie && cookie.length>0 && !req.session.gray) {
      req.session.gray = cookie[0];
    } 
    return cookie;
 }