proxy.build.js 1.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
const proxy = require('http-proxy-middleware');
const ObjectAssign = require('object-assign');
const { chalkError, chalkSuccess } = require('../config/chalk.config');

/**
 *
 * key :
 *  [0]: /api
 *  [1]: target url
 *
 * 预计写法:
 *  1、 /api -> baidu.com : { }
 *  2、 /user : function() { return {} }
 *
 * @param config
 */
module.exports = function(config) {
  console.info(chalkSuccess('build proxy.%s.config 配置!'), process.env.NODE_ENV);

  const proxys = [];
  if (!config) {
    console.log(chalkError('proxy.%s.config 没有配置!'), process.env.NODE_ENV);
  }

  for (const key in config) {
sin's avatar
sin committed
26 27
    let source;
    let target;
28 29
    if (/->/.test(key)) {
      const keys = key.toString().split('->');
sin's avatar
sin committed
30 31 32 33 34 35
      source = keys[0].trim();
      target = keys[1].trim();
    } else {
      source = key;
      target = config[key].target;
    }
sin's avatar
sin committed
36

sin's avatar
sin committed
37 38 39 40 41 42 43
    if (typeof config !== 'object') {
      console.log(
        chalkError('%s: proxy.%s.config 初始化失败 config 类型为 object!'),
        key,
        process.env.NODE_ENV
      );
      break;
44
    }
sin's avatar
sin committed
45 46

    proxys.push(proxy(source, ObjectAssign({ target }, config[key])));
47 48 49 50
  }

  return proxys;
};