_handlers.js 2.6 KB

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