Skip to content

Commit a0a0661

Browse files
committed
refactor: migrate to typescript
1 parent 721dc63 commit a0a0661

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

65 files changed

+7652
-9862
lines changed

.npmrc

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
package-lock=false

.prettierignore

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
dist

.prettierrc

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
{
22
"tabWidth": 2,
3-
"semi": false,
3+
"semi": true,
44
"singleQuote": true
55
}

README.md

+48-42
Original file line numberDiff line numberDiff line change
@@ -15,13 +15,16 @@ Powered by the popular Nodejitsu [`http-proxy`](https://github.com/nodejitsu/nod
1515
Proxy `/api` requests to `http://www.example.org`
1616

1717
```javascript
18-
var express = require('express')
19-
var proxy = require('http-proxy-middleware')
18+
var express = require('express');
19+
var proxy = require('http-proxy-middleware');
2020

21-
var app = express()
21+
var app = express();
2222

23-
app.use('/api', proxy({ target: 'http://www.example.org', changeOrigin: true }))
24-
app.listen(3000)
23+
app.use(
24+
'/api',
25+
proxy({ target: 'http://www.example.org', changeOrigin: true })
26+
);
27+
app.listen(3000);
2528

2629
// http://localhost:3000/api/foo/bar -> http://www.example.org/api/foo/bar
2730
```
@@ -68,9 +71,9 @@ Proxy middleware configuration.
6871
#### proxy([context,] config)
6972

7073
```javascript
71-
var proxy = require('http-proxy-middleware')
74+
var proxy = require('http-proxy-middleware');
7275

73-
var apiProxy = proxy('/api', { target: 'http://www.example.org' })
76+
var apiProxy = proxy('/api', { target: 'http://www.example.org' });
7477
// \____/ \_____________________________/
7578
// | |
7679
// context options
@@ -88,7 +91,7 @@ var apiProxy = proxy('/api', { target: 'http://www.example.org' })
8891

8992
```javascript
9093
// shorthand syntax for the example above:
91-
var apiProxy = proxy('http://www.example.org/api')
94+
var apiProxy = proxy('http://www.example.org/api');
9295
```
9396

9497
More about the [shorthand configuration](#shorthand).
@@ -99,8 +102,8 @@ An example with `express` server.
99102

100103
```javascript
101104
// include dependencies
102-
var express = require('express')
103-
var proxy = require('http-proxy-middleware')
105+
var express = require('express');
106+
var proxy = require('http-proxy-middleware');
104107

105108
// proxy middleware options
106109
var options = {
@@ -116,15 +119,15 @@ var options = {
116119
// override target 'http://www.example.org' to 'http://localhost:8000'
117120
'dev.localhost:3000': 'http://localhost:8000'
118121
}
119-
}
122+
};
120123

121124
// create the proxy (without context)
122-
var exampleProxy = proxy(options)
125+
var exampleProxy = proxy(options);
123126

124127
// mount `exampleProxy` in web server
125-
var app = express()
126-
app.use('/api', exampleProxy)
127-
app.listen(3000)
128+
var app = express();
129+
app.use('/api', exampleProxy);
130+
app.listen(3000);
128131
```
129132

130133
## Context matching
@@ -172,10 +175,10 @@ Providing an alternative way to decide which requests should be proxied; In case
172175
* @return {Boolean}
173176
*/
174177
var filter = function(pathname, req) {
175-
return pathname.match('^/api') && req.method === 'GET'
176-
}
178+
return pathname.match('^/api') && req.method === 'GET';
179+
};
177180

178-
var apiProxy = proxy(filter, { target: 'http://www.example.org' })
181+
var apiProxy = proxy(filter, { target: 'http://www.example.org' });
179182
```
180183

181184
## Options
@@ -224,23 +227,23 @@ Providing an alternative way to decide which requests should be proxied; In case
224227
// simple replace
225228
function logProvider(provider) {
226229
// replace the default console log provider.
227-
return require('winston')
230+
return require('winston');
228231
}
229232
```
230233

231234
```javascript
232235
// verbose replacement
233236
function logProvider(provider) {
234-
var logger = new (require('winston')).Logger()
237+
var logger = new (require('winston')).Logger();
235238

236239
var myCustomProvider = {
237240
log: logger.log,
238241
debug: logger.debug,
239242
info: logger.info,
240243
warn: logger.warn,
241244
error: logger.error
242-
}
243-
return myCustomProvider
245+
};
246+
return myCustomProvider;
244247
}
245248
```
246249

@@ -257,19 +260,19 @@ Subscribe to [http-proxy events](https://github.com/nodejitsu/node-http-proxy#li
257260
function onError(err, req, res) {
258261
res.writeHead(500, {
259262
'Content-Type': 'text/plain'
260-
})
263+
});
261264
res.end(
262265
'Something went wrong. And we are reporting a custom error message.'
263-
)
266+
);
264267
}
265268
```
266269

267270
- **option.onProxyRes**: function, subscribe to http-proxy's `proxyRes` event.
268271

269272
```javascript
270273
function onProxyRes(proxyRes, req, res) {
271-
proxyRes.headers['x-added'] = 'foobar' // add new header to response
272-
delete proxyRes.headers['x-removed'] // remove header from response
274+
proxyRes.headers['x-added'] = 'foobar'; // add new header to response
275+
delete proxyRes.headers['x-removed']; // remove header from response
273276
}
274277
```
275278

@@ -278,7 +281,7 @@ Subscribe to [http-proxy events](https://github.com/nodejitsu/node-http-proxy#li
278281
```javascript
279282
function onProxyReq(proxyReq, req, res) {
280283
// add custom header to request
281-
proxyReq.setHeader('x-added', 'foobar')
284+
proxyReq.setHeader('x-added', 'foobar');
282285
// or log the req
283286
}
284287
```
@@ -288,7 +291,7 @@ Subscribe to [http-proxy events](https://github.com/nodejitsu/node-http-proxy#li
288291
```javascript
289292
function onProxyReqWs(proxyReq, req, socket, options, head) {
290293
// add custom header
291-
proxyReq.setHeader('X-Special-Proxy-Header', 'foobar')
294+
proxyReq.setHeader('X-Special-Proxy-Header', 'foobar');
292295
}
293296
```
294297

@@ -297,15 +300,15 @@ Subscribe to [http-proxy events](https://github.com/nodejitsu/node-http-proxy#li
297300
```javascript
298301
function onOpen(proxySocket) {
299302
// listen for messages coming FROM the target here
300-
proxySocket.on('data', hybiParseAndLogMessage)
303+
proxySocket.on('data', hybiParseAndLogMessage);
301304
}
302305
```
303306

304307
- **option.onClose**: function, subscribe to http-proxy's `close` event.
305308
```javascript
306309
function onClose(res, socket, head) {
307310
// view disconnected websocket connections
308-
console.log('Client disconnected')
311+
console.log('Client disconnected');
309312
}
310313
```
311314

@@ -383,13 +386,13 @@ The following options are provided by the underlying [http-proxy](https://github
383386
Use the shorthand syntax when verbose configuration is not needed. The `context` and `option.target` will be automatically configured when shorthand is used. Options can still be used if needed.
384387
385388
```javascript
386-
proxy('http://www.example.org:8000/api')
389+
proxy('http://www.example.org:8000/api');
387390
// proxy('/api', {target: 'http://www.example.org:8000'});
388391
389-
proxy('http://www.example.org:8000/api/books/*/**.json')
392+
proxy('http://www.example.org:8000/api/books/*/**.json');
390393
// proxy('/api/books/*/**.json', {target: 'http://www.example.org:8000'});
391394
392-
proxy('http://www.example.org:8000/api', { changeOrigin: true })
395+
proxy('http://www.example.org:8000/api', { changeOrigin: true });
393396
// proxy('/api', {target: 'http://www.example.org:8000', changeOrigin: true});
394397
```
395398

@@ -399,7 +402,10 @@ If you want to use the server's `app.use` `path` parameter to match requests;
399402
Create and mount the proxy without the http-proxy-middleware `context` parameter:
400403

401404
```javascript
402-
app.use('/api', proxy({ target: 'http://www.example.org', changeOrigin: true }))
405+
app.use(
406+
'/api',
407+
proxy({ target: 'http://www.example.org', changeOrigin: true })
408+
);
403409
```
404410

405411
`app.use` documentation:
@@ -411,27 +417,27 @@ app.use('/api', proxy({ target: 'http://www.example.org', changeOrigin: true }))
411417

412418
```javascript
413419
// verbose api
414-
proxy('/', { target: 'http://echo.websocket.org', ws: true })
420+
proxy('/', { target: 'http://echo.websocket.org', ws: true });
415421

416422
// shorthand
417-
proxy('http://echo.websocket.org', { ws: true })
423+
proxy('http://echo.websocket.org', { ws: true });
418424

419425
// shorter shorthand
420-
proxy('ws://echo.websocket.org')
426+
proxy('ws://echo.websocket.org');
421427
```
422428

423429
### External WebSocket upgrade
424430

425431
In the previous WebSocket examples, http-proxy-middleware relies on a initial http request in order to listen to the http `upgrade` event. If you need to proxy WebSockets without the initial http request, you can subscribe to the server's http `upgrade` event manually.
426432

427433
```javascript
428-
var wsProxy = proxy('ws://echo.websocket.org', { changeOrigin: true })
434+
var wsProxy = proxy('ws://echo.websocket.org', { changeOrigin: true });
429435

430-
var app = express()
431-
app.use(wsProxy)
436+
var app = express();
437+
app.use(wsProxy);
432438

433-
var server = app.listen(3000)
434-
server.on('upgrade', wsProxy.upgrade) // <-- subscribe to http 'upgrade'
439+
var server = app.listen(3000);
440+
server.on('upgrade', wsProxy.upgrade); // <-- subscribe to http 'upgrade'
435441
```
436442

437443
## Working examples

dist/config-factory.js

+109
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
"use strict";
2+
Object.defineProperty(exports, "__esModule", { value: true });
3+
const _ = require("lodash");
4+
const url = require("url");
5+
const errors_1 = require("./errors");
6+
const logger_1 = require("./logger");
7+
var logger = logger_1.getInstance();
8+
function createConfig(context, opts) {
9+
// structure of config object to be returned
10+
var config = {
11+
context: undefined,
12+
options: {}
13+
};
14+
// app.use('/api', proxy({target:'http://localhost:9000'}));
15+
if (isContextless(context, opts)) {
16+
config.context = '/';
17+
config.options = _.assign(config.options, context);
18+
// app.use('/api', proxy('http://localhost:9000'));
19+
// app.use(proxy('http://localhost:9000/api'));
20+
}
21+
else if (isStringShortHand(context)) {
22+
var oUrl = url.parse(context);
23+
var target = [oUrl.protocol, '//', oUrl.host].join('');
24+
config.context = oUrl.pathname || '/';
25+
config.options = _.assign(config.options, { target: target }, opts);
26+
if (oUrl.protocol === 'ws:' || oUrl.protocol === 'wss:') {
27+
config.options.ws = true;
28+
}
29+
// app.use('/api', proxy({target:'http://localhost:9000'}));
30+
}
31+
else {
32+
config.context = context;
33+
config.options = _.assign(config.options, opts);
34+
}
35+
configureLogger(config.options);
36+
if (!config.options.target) {
37+
throw new Error(errors_1.ERRORS.ERR_CONFIG_FACTORY_TARGET_MISSING);
38+
}
39+
// Legacy option.proxyHost
40+
config.options = mapLegacyProxyHostOption(config.options);
41+
// Legacy option.proxyTable > option.router
42+
config.options = mapLegacyProxyTableOption(config.options);
43+
return config;
44+
}
45+
exports.createConfig = createConfig;
46+
/**
47+
* Checks if a String only target/config is provided.
48+
* This can be just the host or with the optional path.
49+
*
50+
* @example
51+
* app.use('/api', proxy('http://localhost:9000'));
52+
app.use(proxy('http://localhost:9000/api'));
53+
*
54+
* @param {String} context [description]
55+
* @return {Boolean} [description]
56+
*/
57+
function isStringShortHand(context) {
58+
if (_.isString(context)) {
59+
return !!url.parse(context).host;
60+
}
61+
}
62+
/**
63+
* Checks if a Object only config is provided, without a context.
64+
* In this case the all paths will be proxied.
65+
*
66+
* @example
67+
* app.use('/api', proxy({target:'http://localhost:9000'}));
68+
*
69+
* @param {Object} context [description]
70+
* @param {*} opts [description]
71+
* @return {Boolean} [description]
72+
*/
73+
function isContextless(context, opts) {
74+
return _.isPlainObject(context) && _.isEmpty(opts);
75+
}
76+
function mapLegacyProxyHostOption(options) {
77+
// set options.headers.host when option.proxyHost is provided
78+
if (options.proxyHost) {
79+
logger.warn('*************************************');
80+
logger.warn('[HPM] Deprecated "option.proxyHost"');
81+
logger.warn(' Use "option.changeOrigin" or "option.headers.host" instead');
82+
logger.warn(' "option.proxyHost" will be removed in future release.');
83+
logger.warn('*************************************');
84+
options.headers = options.headers || {};
85+
options.headers.host = options.proxyHost;
86+
}
87+
return options;
88+
}
89+
// Warn deprecated proxyTable api usage
90+
function mapLegacyProxyTableOption(options) {
91+
if (options.proxyTable) {
92+
logger.warn('*************************************');
93+
logger.warn('[HPM] Deprecated "option.proxyTable"');
94+
logger.warn(' Use "option.router" instead');
95+
logger.warn(' "option.proxyTable" will be removed in future release.');
96+
logger.warn('*************************************');
97+
options.router = _.clone(options.proxyTable);
98+
_.omit(options, 'proxyTable');
99+
}
100+
return options;
101+
}
102+
function configureLogger(options) {
103+
if (options.logLevel) {
104+
logger.setLevel(options.logLevel);
105+
}
106+
if (options.logProvider) {
107+
logger.setProvider(options.logProvider);
108+
}
109+
}

0 commit comments

Comments
 (0)