handlers.js 1.9 KB

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