All files / koa-proxy-middleware/lib/base handle.js

85.71% Statements 18/21
81.25% Branches 13/16
75% Functions 3/4
85.71% Lines 18/21
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 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40  1x             1x 2x 2x 9x     9x 9x   4x 1x 3x 2x   4x 3x 3x       2x 8x 7x     2x            
'use strict';
const queryString = require('querystring');
 
/**
 * 处理钩子函数、处理bodyparser post请求
 * @param {*} proxyServer 代理服务
 * @param {*} option 处理后的参数
 */
module.exports = (proxyServer, option) => {
  const { handleReq, handleRes, handleError } = option;
  proxyServer.on('proxyReq', (proxyReq, req, res, options) => {
    Iif (handleReq) {
      handleReq.call(null, { proxyReq, req, res, options });
    }
    const contentType = proxyReq.getHeader('Content-Type');
    if (req.body && contentType) {
      let bodyData;
      if (contentType.match(/application\/json/)) {
        bodyData = JSON.stringify(req.body);
      } else if (contentType.match(/application\/x-www-form-urlencoded/)) {
        bodyData = queryString.stringify(req.body);
      }
      if (bodyData) {
        proxyReq.write(bodyData);
        proxyReq.end();
      }
    }
  });
  proxyServer.on('proxyRes', (proxyRes, req, res) => {
    if (handleRes) {
      handleRes.call(null, { proxyRes, req, res });
    }
  });
  proxyServer.on('error', (err, req, res) => {
    if (handleError) {
      handleError.call(null, { err, req, res });
    }
  });
};