UNPKG

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