source: trip-planner-front/node_modules/http-proxy-middleware/lib/handlers.js@ 1ad8e64

Last change on this file since 1ad8e64 was 6a3a178, checked in by Ema <ema_spirova@…>, 3 years ago

initial commit

  • Property mode set to 100644
File size: 2.0 KB
RevLine 
[6a3a178]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 = [
22 'error',
23 'proxyReq',
24 'proxyReqWs',
25 'proxyRes',
26 'open',
27 'close'
28 ]
29 var handlers = {}
30
31 _.forEach(proxyEvents, function(event) {
32 // all handlers for the http-proxy events are prefixed with 'on'.
33 // loop through options and try to find these handlers
34 // and add them to the handlers object for subscription in init().
35 var eventName = _.camelCase('on ' + event)
36 var fnHandler = _.get(opts, eventName)
37
38 if (_.isFunction(fnHandler)) {
39 handlers[event] = fnHandler
40 }
41 })
42
43 // add default error handler in absence of error handler
44 if (!_.isFunction(handlers.error)) {
45 handlers.error = defaultErrorHandler
46 }
47
48 // add default close handler in absence of close handler
49 if (!_.isFunction(handlers.close)) {
50 handlers.close = logClose
51 }
52
53 return handlers
54}
55
56function defaultErrorHandler(err, req, res) {
57 var host = req.headers && req.headers.host
58 var code = err.code
59
60 if (res.writeHead && !res.headersSent) {
61 if (/HPE_INVALID/.test(code)) {
62 res.writeHead(502)
63 } else {
64 switch (code) {
65 case 'ECONNRESET':
66 case 'ENOTFOUND':
67 case 'ECONNREFUSED':
68 res.writeHead(504)
69 break
70 default:
71 res.writeHead(500)
72 }
73 }
74 }
75
76 res.end('Error occured while trying to proxy to: ' + host + req.url)
77}
78
79function logClose(req, socket, head) {
80 // view disconnected websocket connections
81 logger.info('[HPM] Client disconnected')
82}
Note: See TracBrowser for help on using the repository browser.