handlers.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.getHandlers = exports.init = void 0;
  4. const camelcase = require("camelcase");
  5. const logger_1 = require("./logger");
  6. const logger = logger_1.getInstance();
  7. function init(proxy, option) {
  8. const handlers = getHandlers(option);
  9. for (const eventName of Object.keys(handlers)) {
  10. proxy.on(eventName, handlers[eventName]);
  11. }
  12. logger.debug('[HPM] Subscribed to http-proxy events:', Object.keys(handlers));
  13. }
  14. exports.init = init;
  15. function getHandlers(options) {
  16. // https://github.com/nodejitsu/node-http-proxy#listening-for-proxy-events
  17. const proxyEvents = ['error', 'proxyReq', 'proxyReqWs', 'proxyRes', 'open', 'close'];
  18. const handlers = {};
  19. for (const event of proxyEvents) {
  20. // all handlers for the http-proxy events are prefixed with 'on'.
  21. // loop through options and try to find these handlers
  22. // and add them to the handlers object for subscription in init().
  23. const eventName = camelcase('on ' + event);
  24. const fnHandler = options ? options[eventName] : null;
  25. if (typeof fnHandler === 'function') {
  26. handlers[event] = fnHandler;
  27. }
  28. }
  29. // add default error handler in absence of error handler
  30. if (typeof handlers.error !== 'function') {
  31. handlers.error = defaultErrorHandler;
  32. }
  33. // add default close handler in absence of close handler
  34. if (typeof handlers.close !== 'function') {
  35. handlers.close = logClose;
  36. }
  37. return handlers;
  38. }
  39. exports.getHandlers = getHandlers;
  40. function defaultErrorHandler(err, req, res) {
  41. const host = req.headers && req.headers.host;
  42. const code = err.code;
  43. if (res.writeHead && !res.headersSent) {
  44. if (/HPE_INVALID/.test(code)) {
  45. res.writeHead(502);
  46. }
  47. else {
  48. switch (code) {
  49. case 'ECONNRESET':
  50. case 'ENOTFOUND':
  51. case 'ECONNREFUSED':
  52. case 'ETIMEDOUT':
  53. res.writeHead(504);
  54. break;
  55. default:
  56. res.writeHead(500);
  57. }
  58. }
  59. }
  60. res.end(`Error occured while trying to proxy: ${host}${req.url}`);
  61. }
  62. function logClose(req, socket, head) {
  63. // view disconnected websocket connections
  64. logger.info('[HPM] Client disconnected');
  65. }