index.js 2.29 KB
var http = require('http'),
    conf = require("./conf");
var request = require('request');
var express = require('express');
var app = express();
var bodyParser = require('body-parser'); //body序列化插件

app.use(bodyParser.urlencoded({extended: false}));

var SERVICE_URL = "/service.api.yohobuy.com";//新服务的URL

app.get('/test',function(req,res,next){
    res.send('hi~~~');
});

/**
 * 路由生成
 */
function route() {
 
  for(var i=0;i<conf.apis.length;i++) {

   var api = conf.apis[i];

   for(var j=0;j<api.methods.length;j++){

       if(api.route === SERVICE_URL) {
          api.route += '/*';
       }
       console.log('method: ['+api.methods[j]+'] route:'+api.route);

       app[api.methods[j]](api.route, function(req, res, next) {
            var form = req.body?req.body:{};
            var url = whiteProc('http:/'+req.url,form,req.query);
            
            console.log('call method:'+req.method+' url:'+url);
            procRes(req.method,url,req.body,res);
       });
   }
  }
}

/**
 * 白名单处理
 * @param  {[type]} url  [description]
 * @param  {[type]} form [description]
 * @param  {[query]} query [description]
 * @return {[type]}      [description]
 */
function whiteProc(url,form,query) {

    var list = conf.whiteList;
    var method = query.method?query.method:form['method'];
    method = method?method:'';

    for(var i=0;i<list.length;i++) {
        if(url.indexOf(list[i].api)>-1||method === list[i].api) {

           console.log('match api:'+list[i].api+' map:'+ list[i].map);
           return list[i].map;
        }
    }
    console.log('no match url:'+url);
    return url;
}

/**
 * 处理代理参数
 * @param  {string} method  方法
 * @param  {string} url  代理地址
 * @param  {Object} form 表单数据
 * @param  {Object} res  响应信息
 * @return {void} 
 */
function procRes(method,url,form, ress) {
    if(method === "GET") {
       request(url,callback);
    } else {
       request.post({url:url, form: form},callback);
    }

    function callback(err,res,body){
      if (!err && res.statusCode == 200) {
        ress.send(body); 
      }
      else {
        if(res) {
          console.log('errorCode:'+res.statusCode);
        }
        console.log(err);
        ress.send(body);
      }
    } 
}

console.log('app start!');
route();
app.listen(3000);