Projekt

Obecné

Profil

Stáhnout (5.04 KB) Statistiky
| Větev: | Revize:
1
var _ = require('lodash')
2
var httpProxy = require('http-proxy')
3
var configFactory = require('./config-factory')
4
var handlers = require('./handlers')
5
var contextMatcher = require('./context-matcher')
6
var PathRewriter = require('./path-rewriter')
7
var Router = require('./router')
8
var logger = require('./logger').getInstance()
9
var getArrow = require('./logger').getArrow
10

    
11
module.exports = HttpProxyMiddleware
12

    
13
function HttpProxyMiddleware(context, opts) {
14
  // https://github.com/chimurai/http-proxy-middleware/issues/57
15
  var wsUpgradeDebounced = _.debounce(handleUpgrade)
16
  var wsInitialized = false
17
  var config = configFactory.createConfig(context, opts)
18
  var proxyOptions = config.options
19

    
20
  // create proxy
21
  var proxy = httpProxy.createProxyServer({})
22
  logger.info(
23
    '[HPM] Proxy created:',
24
    config.context,
25
    ' -> ',
26
    proxyOptions.target
27
  )
28

    
29
  var pathRewriter = PathRewriter.create(proxyOptions.pathRewrite) // returns undefined when "pathRewrite" is not provided
30

    
31
  // attach handler to http-proxy events
32
  handlers.init(proxy, proxyOptions)
33

    
34
  // log errors for debug purpose
35
  proxy.on('error', logError)
36

    
37
  // https://github.com/chimurai/http-proxy-middleware/issues/19
38
  // expose function to upgrade externally
39
  middleware.upgrade = wsUpgradeDebounced
40

    
41
  return middleware
42

    
43
  function middleware(req, res, next) {
44
    if (shouldProxy(config.context, req)) {
45
      var activeProxyOptions = prepareProxyRequest(req)
46
      proxy.web(req, res, activeProxyOptions)
47
    } else {
48
      next()
49
    }
50

    
51
    if (proxyOptions.ws === true) {
52
      // use initial request to access the server object to subscribe to http upgrade event
53
      catchUpgradeRequest(req.connection.server)
54
    }
55
  }
56

    
57
  function catchUpgradeRequest(server) {
58
    // subscribe once; don't subscribe on every request...
59
    // https://github.com/chimurai/http-proxy-middleware/issues/113
60
    if (!wsInitialized) {
61
      server.on('upgrade', wsUpgradeDebounced)
62
      wsInitialized = true
63
    }
64
  }
65

    
66
  function handleUpgrade(req, socket, head) {
67
    // set to initialized when used externally
68
    wsInitialized = true
69

    
70
    if (shouldProxy(config.context, req)) {
71
      var activeProxyOptions = prepareProxyRequest(req)
72
      proxy.ws(req, socket, head, activeProxyOptions)
73
      logger.info('[HPM] Upgrading to WebSocket')
74
    }
75
  }
76

    
77
  /**
78
   * Determine whether request should be proxied.
79
   *
80
   * @private
81
   * @param  {String} context [description]
82
   * @param  {Object} req     [description]
83
   * @return {Boolean}
84
   */
85
  function shouldProxy(context, req) {
86
    var path = req.originalUrl || req.url
87
    return contextMatcher.match(context, path, req)
88
  }
89

    
90
  /**
91
   * Apply option.router and option.pathRewrite
92
   * Order matters:
93
   *    Router uses original path for routing;
94
   *    NOT the modified path, after it has been rewritten by pathRewrite
95
   * @param {Object} req
96
   * @return {Object} proxy options
97
   */
98
  function prepareProxyRequest(req) {
99
    // https://github.com/chimurai/http-proxy-middleware/issues/17
100
    // https://github.com/chimurai/http-proxy-middleware/issues/94
101
    req.url = req.originalUrl || req.url
102

    
103
    // store uri before it gets rewritten for logging
104
    var originalPath = req.url
105
    var newProxyOptions = _.assign({}, proxyOptions)
106

    
107
    // Apply in order:
108
    // 1. option.router
109
    // 2. option.pathRewrite
110
    __applyRouter(req, newProxyOptions)
111
    __applyPathRewrite(req, pathRewriter)
112

    
113
    // debug logging for both http(s) and websockets
114
    if (proxyOptions.logLevel === 'debug') {
115
      var arrow = getArrow(
116
        originalPath,
117
        req.url,
118
        proxyOptions.target,
119
        newProxyOptions.target
120
      )
121
      logger.debug(
122
        '[HPM] %s %s %s %s',
123
        req.method,
124
        originalPath,
125
        arrow,
126
        newProxyOptions.target
127
      )
128
    }
129

    
130
    return newProxyOptions
131
  }
132

    
133
  // Modify option.target when router present.
134
  function __applyRouter(req, options) {
135
    var newTarget
136

    
137
    if (options.router) {
138
      newTarget = Router.getTarget(req, options)
139

    
140
      if (newTarget) {
141
        logger.debug(
142
          '[HPM] Router new target: %s -> "%s"',
143
          options.target,
144
          newTarget
145
        )
146
        options.target = newTarget
147
      }
148
    }
149
  }
150

    
151
  // rewrite path
152
  function __applyPathRewrite(req, pathRewriter) {
153
    if (pathRewriter) {
154
      var path = pathRewriter(req.url, req)
155

    
156
      if (typeof path === 'string') {
157
        req.url = path
158
      } else {
159
        logger.info('[HPM] pathRewrite: No rewritten path found. (%s)', req.url)
160
      }
161
    }
162
  }
163

    
164
  function logError(err, req, res) {
165
    var hostname =
166
      (req.headers && req.headers.host) || (req.hostname || req.host) // (websocket) || (node0.10 || node 4/5)
167
    var target = proxyOptions.target.host || proxyOptions.target
168
    var errorMessage =
169
      '[HPM] Error occurred while trying to proxy request %s from %s to %s (%s) (%s)'
170
    var errReference =
171
      'https://nodejs.org/api/errors.html#errors_common_system_errors' // link to Node Common Systems Errors page
172

    
173
    logger.error(
174
      errorMessage,
175
      req.url,
176
      hostname,
177
      target,
178
      err.code || err,
179
      errReference
180
    )
181
  }
182
}
(5-5/8)