diff --git a/.prettierrc b/.prettierrc index 6a8af5e9..c9df194d 100644 --- a/.prettierrc +++ b/.prettierrc @@ -1,4 +1,5 @@ { + "printWidth": 100, "tabWidth": 2, "semi": true, "singleQuote": true diff --git a/CHANGELOG.md b/CHANGELOG.md index 54b6876e..6db71872 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,9 +1,15 @@ # Changelog +## next + +- feat(createProxyMiddleware): explicit import http-proxy-middleware (BREAKING CHANGE)([#400](https://github.com/chimurai/http-proxy-middleware/issues/400#issuecomment-587162378)) +- feat(typescript): export http-proxy-middleware types ([#400](https://github.com/chimurai/http-proxy-middleware/issues/400)) +- fix(typescript): ES6 target - TS1192 ([#400](https://github.com/chimurai/http-proxy-middleware/issues/400#issuecomment-587064349)) + ## [v0.21.0](https://github.com/chimurai/http-proxy-middleware/releases/tag/v0.21.0) - feat(http-proxy): bump to v1.18.0 -- feat: async router ([#379](https://github.com/chimurai/http-proxy-middleware/issues/335)) ([LiranBri](https://github.com/LiranBri)) +- feat: async router ([#379](https://github.com/chimurai/http-proxy-middleware/issues/379)) ([LiranBri](https://github.com/LiranBri)) - feat(typescript): types support ([#369](https://github.com/chimurai/http-proxy-middleware/pull/369)) - feat: async pathRewrite ([#397](https://github.com/chimurai/http-proxy-middleware/pull/397)) ([rsethc](https://github.com/rsethc)) diff --git a/README.md b/README.md index 688a3fe3..3beafc06 100644 --- a/README.md +++ b/README.md @@ -10,20 +10,40 @@ Node.js proxying made simple. Configure proxy middleware with ease for [connect] Powered by the popular Nodejitsu [`http-proxy`](https://github.com/nodejitsu/node-http-proxy). [![GitHub stars](https://img.shields.io/github/stars/nodejitsu/node-http-proxy.svg?style=social&label=Star)](https://github.com/nodejitsu/node-http-proxy) +## ⚠️ NOTE + +This page is showing documentation for version v1.x.x + +If you're looking for v0.x documentation. Go to: +https://github.com/chimurai/http-proxy-middleware/tree/v0.21.0#readme + ## TL;DR Proxy `/api` requests to `http://www.example.org` ```javascript -var express = require('express'); -var proxy = require('http-proxy-middleware'); +// javascript + +const express = require('express'); +const { createProxyMiddleware } = require('http-proxy-middleware'); -var app = express(); +const app = express(); -app.use( - '/api', - proxy({ target: 'http://www.example.org', changeOrigin: true }) -); +app.use('/api', createProxyMiddleware({ target: 'http://www.example.org', changeOrigin: true })); +app.listen(3000); + +// http://localhost:3000/api/foo/bar -> http://www.example.org/api/foo/bar +``` + +```typescript +// typescript + +import * as express from 'express'; +import { createProxyMiddleware, Filter, Options, RequestHandler } from 'http-proxy-middleware'; + +const app = express(); + +app.use('/api', createProxyMiddleware({ target: 'http://www.example.org', changeOrigin: true })); app.listen(3000); // http://localhost:3000/api/foo/bar -> http://www.example.org/api/foo/bar @@ -68,15 +88,15 @@ $ npm install --save-dev http-proxy-middleware Proxy middleware configuration. -#### proxy([context,] config) +#### createProxyMiddleware([context,] config) ```javascript -var proxy = require('http-proxy-middleware'); +const { createProxyMiddleware } = require('http-proxy-middleware'); -var apiProxy = proxy('/api', { target: 'http://www.example.org' }); -// \____/ \_____________________________/ -// | | -// context options +const apiProxy = createProxyMiddleware('/api', { target: 'http://www.example.org' }); +// \____/ \_____________________________/ +// | | +// context options // 'apiProxy' is now ready to be used as middleware in a server. ``` @@ -87,11 +107,11 @@ var apiProxy = proxy('/api', { target: 'http://www.example.org' }); (full list of [`http-proxy-middleware` configuration options](#options)) -#### proxy(uri [, config]) +#### createProxyMiddleware(uri [, config]) ```javascript // shorthand syntax for the example above: -var apiProxy = proxy('http://www.example.org/api'); +const apiProxy = createProxyMiddleware('http://www.example.org/api'); ``` More about the [shorthand configuration](#shorthand). @@ -102,11 +122,11 @@ An example with `express` server. ```javascript // include dependencies -var express = require('express'); -var proxy = require('http-proxy-middleware'); +const express = require('express'); +const { createProxyMiddleware } = require('http-proxy-middleware'); // proxy middleware options -var options = { +const options = { target: 'http://www.example.org', // target host changeOrigin: true, // needed for virtual hosted sites ws: true, // proxy websockets @@ -122,10 +142,10 @@ var options = { }; // create the proxy (without context) -var exampleProxy = proxy(options); +const exampleProxy = createProxyMiddleware(options); // mount `exampleProxy` in web server -var app = express(); +const app = express(); app.use('/api', exampleProxy); app.listen(3000); ``` @@ -145,24 +165,24 @@ Providing an alternative way to decide which requests should be proxied; In case - **path matching** - - `proxy({...})` - matches any path, all requests will be proxied. - - `proxy('/', {...})` - matches any path, all requests will be proxied. - - `proxy('/api', {...})` - matches paths starting with `/api` + - `createProxyMiddleware({...})` - matches any path, all requests will be proxied. + - `createProxyMiddleware('/', {...})` - matches any path, all requests will be proxied. + - `createProxyMiddleware('/api', {...})` - matches paths starting with `/api` - **multiple path matching** - - `proxy(['/api', '/ajax', '/someotherpath'], {...})` + - `createProxyMiddleware(['/api', '/ajax', '/someotherpath'], {...})` - **wildcard path matching** For fine-grained control you can use wildcard matching. Glob pattern matching is done by _micromatch_. Visit [micromatch](https://www.npmjs.com/package/micromatch) or [glob](https://www.npmjs.com/package/glob) for more globbing examples. - - `proxy('**', {...})` matches any path, all requests will be proxied. - - `proxy('**/*.html', {...})` matches any path which ends with `.html` - - `proxy('/*.html', {...})` matches paths directly under path-absolute - - `proxy('/api/**/*.html', {...})` matches requests ending with `.html` in the path of `/api` - - `proxy(['/api/**', '/ajax/**'], {...})` combine multiple patterns - - `proxy(['/api/**', '!**/bad.json'], {...})` exclusion + - `createProxyMiddleware('**', {...})` matches any path, all requests will be proxied. + - `createProxyMiddleware('**/*.html', {...})` matches any path which ends with `.html` + - `createProxyMiddleware('/*.html', {...})` matches paths directly under path-absolute + - `createProxyMiddleware('/api/**/*.html', {...})` matches requests ending with `.html` in the path of `/api` + - `createProxyMiddleware(['/api/**', '/ajax/**'], {...})` combine multiple patterns + - `createProxyMiddleware(['/api/**', '!**/bad.json'], {...})` exclusion **Note**: In multiple path matching, you cannot use string paths and wildcard paths together. @@ -174,11 +194,13 @@ Providing an alternative way to decide which requests should be proxied; In case /** * @return {Boolean} */ - var filter = function(pathname, req) { + const filter = function(pathname, req) { return pathname.match('^/api') && req.method === 'GET'; }; - var apiProxy = proxy(filter, { target: 'http://www.example.org' }); + const apiProxy = createProxyMiddleware(filter, { + target: 'http://www.example.org' + }); ``` ## Options @@ -202,7 +224,7 @@ Providing an alternative way to decide which requests should be proxied; In case // custom rewriting, returning Promise pathRewrite: async function (path, req) { - var should_add_something = await httpRequestToDecideSomething(path); + const should_add_something = await httpRequestToDecideSomething(path); if (should_add_something) path += "something"; return path; } @@ -248,9 +270,9 @@ Providing an alternative way to decide which requests should be proxied; In case ```javascript // verbose replacement function logProvider(provider) { - var logger = new (require('winston').Logger)(); + const logger = new (require('winston').Logger)(); - var myCustomProvider = { + const myCustomProvider = { log: logger.log, debug: logger.debug, info: logger.info, @@ -272,9 +294,7 @@ Subscribe to [http-proxy events](https://github.com/nodejitsu/node-http-proxy#li res.writeHead(500, { 'Content-Type': 'text/plain' }); - res.end( - 'Something went wrong. And we are reporting a custom error message.' - ); + res.end('Something went wrong. And we are reporting a custom error message.'); } ``` @@ -401,14 +421,14 @@ The following options are provided by the underlying [http-proxy](https://github 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. ```javascript -proxy('http://www.example.org:8000/api'); -// proxy('/api', {target: 'http://www.example.org:8000'}); +createProxyMiddleware('http://www.example.org:8000/api'); +// createProxyMiddleware('/api', {target: 'http://www.example.org:8000'}); -proxy('http://www.example.org:8000/api/books/*/**.json'); -// proxy('/api/books/*/**.json', {target: 'http://www.example.org:8000'}); +createProxyMiddleware('http://www.example.org:8000/api/books/*/**.json'); +// createProxyMiddleware('/api/books/*/**.json', {target: 'http://www.example.org:8000'}); -proxy('http://www.example.org:8000/api', { changeOrigin: true }); -// proxy('/api', {target: 'http://www.example.org:8000', changeOrigin: true}); +createProxyMiddleware('http://www.example.org:8000/api', { changeOrigin: true }); +// createProxyMiddleware('/api', {target: 'http://www.example.org:8000', changeOrigin: true}); ``` ### app.use(path, proxy) @@ -417,10 +437,7 @@ If you want to use the server's `app.use` `path` parameter to match requests; Create and mount the proxy without the http-proxy-middleware `context` parameter: ```javascript -app.use( - '/api', - proxy({ target: 'http://www.example.org', changeOrigin: true }) -); +app.use('/api', createProxyMiddleware({ target: 'http://www.example.org', changeOrigin: true })); ``` `app.use` documentation: @@ -433,13 +450,13 @@ app.use( ```javascript // verbose api -proxy('/', { target: 'http://echo.websocket.org', ws: true }); +createProxyMiddleware('/', { target: 'http://echo.websocket.org', ws: true }); // shorthand -proxy('http://echo.websocket.org', { ws: true }); +createProxyMiddleware('http://echo.websocket.org', { ws: true }); // shorter shorthand -proxy('ws://echo.websocket.org'); +createProxyMiddleware('ws://echo.websocket.org'); ``` ### External WebSocket upgrade @@ -447,12 +464,12 @@ proxy('ws://echo.websocket.org'); 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. ```javascript -var wsProxy = proxy('ws://echo.websocket.org', { changeOrigin: true }); +const wsProxy = createProxyMiddleware('ws://echo.websocket.org', { changeOrigin: true }); -var app = express(); +const app = express(); app.use(wsProxy); -var server = app.listen(3000); +const server = app.listen(3000); server.on('upgrade', wsProxy.upgrade); // <-- subscribe to http 'upgrade' ``` diff --git a/examples/README.md b/examples/README.md index e139e50a..25381bb0 100644 --- a/examples/README.md +++ b/examples/README.md @@ -7,7 +7,8 @@ To run and view the [examples](https://github.com/chimurai/http-proxy-middleware ```bash $ git clone https://github.com/chimurai/http-proxy-middleware.git $ cd http-proxy-middleware -$ npm install +$ yarn +$ yarn build ``` Run the example from root folder: diff --git a/examples/_proxy.js b/examples/_proxy.js deleted file mode 100644 index 16970325..00000000 --- a/examples/_proxy.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = require('../dist/index'); diff --git a/examples/browser-sync/index.js b/examples/browser-sync/index.js index 22ff553e..c211b3dd 100644 --- a/examples/browser-sync/index.js +++ b/examples/browser-sync/index.js @@ -1,13 +1,13 @@ /** * Module dependencies. */ -var browserSync = require('browser-sync').create(); -var proxy = require('../_proxy'); // require('http-proxy-middleware'); +const browserSync = require('browser-sync').create(); +const { createProxyMiddleware } = require('../../dist'); // require('http-proxy-middleware'); /** * Configure proxy middleware */ -var jsonPlaceholderProxy = proxy('/users', { +const jsonPlaceholderProxy = createProxyMiddleware('/users', { target: 'http://jsonplaceholder.typicode.com', changeOrigin: true, // for vhosted sites, changes host header to match to target's host logLevel: 'debug' diff --git a/examples/connect/index.js b/examples/connect/index.js index 9c23ed84..041ba11c 100644 --- a/examples/connect/index.js +++ b/examples/connect/index.js @@ -1,20 +1,20 @@ /** * Module dependencies. */ -var http = require('http'); -var connect = require('connect'); -var proxy = require('../_proxy'); // require('http-proxy-middleware'); +const http = require('http'); +const connect = require('connect'); +const { createProxyMiddleware } = require('../../dist'); // require('http-proxy-middleware'); /** * Configure proxy middleware */ -var jsonPlaceholderProxy = proxy({ +const jsonPlaceholderProxy = createProxyMiddleware({ target: 'http://jsonplaceholder.typicode.com', changeOrigin: true, // for vhosted sites, changes host header to match to target's host logLevel: 'debug' }); -var app = connect(); +const app = connect(); /** * Add the proxy to connect diff --git a/examples/express/index.js b/examples/express/index.js index 0951a16e..ee457199 100644 --- a/examples/express/index.js +++ b/examples/express/index.js @@ -1,19 +1,19 @@ /** * Module dependencies. */ -var express = require('express'); -var proxy = require('../_proxy'); // require('http-proxy-middleware'); +const express = require('express'); +const { createProxyMiddleware } = require('../../dist'); // require('http-proxy-middleware'); /** * Configure proxy middleware */ -var jsonPlaceholderProxy = proxy({ +const jsonPlaceholderProxy = createProxyMiddleware({ target: 'http://jsonplaceholder.typicode.com', changeOrigin: true, // for vhosted sites, changes host header to match to target's host logLevel: 'debug' }); -var app = express(); +const app = express(); /** * Add the proxy to express diff --git a/examples/websocket/index.js b/examples/websocket/index.js index 8a0f3acb..43d7ffed 100644 --- a/examples/websocket/index.js +++ b/examples/websocket/index.js @@ -1,13 +1,13 @@ /** * Module dependencies. */ -var express = require('express'); -var proxy = require('../_proxy'); // require('http-proxy-middleware'); +const express = require('express'); +const { createProxyMiddleware } = require('../../dist'); // require('http-proxy-middleware'); /** * Configure proxy middleware */ -var wsProxy = proxy('/', { +const wsProxy = createProxyMiddleware('/', { target: 'http://echo.websocket.org', // pathRewrite: { // '^/websocket' : '/socket', // rewrite path. @@ -18,11 +18,11 @@ var wsProxy = proxy('/', { logLevel: 'debug' }); -var app = express(); +const app = express(); app.use('/', express.static(__dirname)); // demo page app.use(wsProxy); // add the proxy to express -var server = app.listen(3000); +const server = app.listen(3000); server.on('upgrade', wsProxy.upgrade); // optional: upgrade externally console.log('[DEMO] Server: listening on port 3000'); @@ -34,7 +34,7 @@ require('open')('http://localhost:3000'); * Example: * Open http://localhost:3000 in WebSocket compatible browser. * In browser console: - * 1. `var socket = new WebSocket('ws://localhost:3000');` // create new WebSocket + * 1. `const socket = new WebSocket('ws://localhost:3000');` // create new WebSocket * 2. `socket.onmessage = function (msg) {console.log(msg)};` // listen to socket messages * 3. `socket.send('hello world');` // send message * > {data: "hello world"} // server should echo back your message. diff --git a/package.json b/package.json index c376cf5d..8ad3898d 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "http-proxy-middleware", - "version": "0.21.0", + "version": "0.22.0-alpha", "description": "The one-liner node.js proxy middleware for connect, express and browser-sync", "main": "dist/index.js", "types": "dist/index.d.ts", @@ -48,7 +48,7 @@ "bugs": { "url": "https://github.com/chimurai/http-proxy-middleware/issues" }, - "homepage": "https://github.com/chimurai/http-proxy-middleware", + "homepage": "https://github.com/chimurai/http-proxy-middleware#readme", "devDependencies": { "@commitlint/cli": "^8.0.0", "@commitlint/config-conventional": "^8.0.0", diff --git a/recipes/README.md b/recipes/README.md index 8caa20f8..afd54843 100644 --- a/recipes/README.md +++ b/recipes/README.md @@ -9,18 +9,18 @@ Overview of `http-proxy-middleware` specific options. http-proxy-middleware uses Nodejitsu's [http-proxy](https://github.com/nodejitsu/node-http-proxy) to do the actual proxying. All of its [options](https://github.com/nodejitsu/node-http-proxy#options) are exposed via http-proxy-middleware's configuration object. ```javascript -var proxy = require('http-proxy-middleware'); -var winston = require('winston'); +const { createProxyMiddleware } = require('http-proxy-middleware'); +const winston = require('winston'); /** * Context matching: decide which path(s) should be proxied. (wildcards supported) **/ -var context = '/api'; +const context = '/api'; /** * Proxy options */ -var options = { +const options = { // hostname to the target server target: 'http://localhost:3000', @@ -104,5 +104,5 @@ var options = { /** * Create the proxy middleware, so it can be used in a server. */ -var apiProxy = proxy(context, options); +const apiProxy = createProxyMiddleware(context, options); ``` diff --git a/recipes/basic.md b/recipes/basic.md index e14f5ddc..c22b0957 100644 --- a/recipes/basic.md +++ b/recipes/basic.md @@ -3,12 +3,12 @@ This example will create a basic proxy middleware. ```javascript -var proxy = require('http-proxy-middleware'); +const { createProxyMiddleware } = require('http-proxy-middleware'); -var apiProxy = proxy('/api', { target: 'http://localhost:3000' }); -// \____/ \________________________________/ -// | | -// context options +const apiProxy = createProxyMiddleware('/api', { target: 'http://localhost:3000' }); +// \____/ \________________________________/ +// | | +// context options ``` ## Alternative configuration @@ -16,17 +16,17 @@ var apiProxy = proxy('/api', { target: 'http://localhost:3000' }); The proxy behavior of the following examples are **exactly** the same; Just different ways to configure it. ```javascript -app.use(proxy('/api', { target: 'http://localhost:3000', changeOrigin: true })); +app.use(createProxyMiddleware('/api', { target: 'http://localhost:3000', changeOrigin: true })); ``` ```javascript -app.use(proxy('http://localhost:3000/api', { changeOrigin: true })); +app.use(createProxyMiddleware('http://localhost:3000/api', { changeOrigin: true })); ``` ```javascript -app.use('/api', proxy('http://localhost:3000', { changeOrigin: true })); +app.use('/api', createProxyMiddleware('http://localhost:3000', { changeOrigin: true })); ``` ```javascript -app.use('/api', proxy({ target: 'http://localhost:3000', changeOrigin: true })); +app.use('/api', createProxyMiddleware({ target: 'http://localhost:3000', changeOrigin: true })); ``` diff --git a/recipes/context-matching.md b/recipes/context-matching.md index 9d7a6cea..af422863 100644 --- a/recipes/context-matching.md +++ b/recipes/context-matching.md @@ -31,9 +31,11 @@ The [RFC 3986 `path`](https://tools.ietf.org/html/rfc3986#section-3.3) is used f This will match paths starting with `/api` ```javascript -var proxy = require('http-proxy-middleware'); +const { createProxyMiddleware } = require('http-proxy-middleware'); -var apiProxy = proxy('/api', { target: 'http://localhost:3000' }); +const apiProxy = createProxyMiddleware('/api', { + target: 'http://localhost:3000' +}); // `/api/foo/bar` -> `http://localhost:3000/api/foo/bar` ``` @@ -43,9 +45,9 @@ var apiProxy = proxy('/api', { target: 'http://localhost:3000' }); This will match paths starting with `/api` or `/rest` ```javascript -var proxy = require('http-proxy-middleware'); +const { createProxyMiddleware } = require('http-proxy-middleware'); -var apiProxy = proxy(['/api', '/rest'], { target: 'http://localhost:3000' }); +const apiProxy = createProxyMiddleware(['/api', '/rest'], { target: 'http://localhost:3000' }); // `/api/foo/bar` -> `http://localhost:3000/api/foo/bar` // `/rest/lorum/ipsum` -> `http://localhost:3000/rest/lorum/ipsum` @@ -56,9 +58,11 @@ var apiProxy = proxy(['/api', '/rest'], { target: 'http://localhost:3000' }); This will match paths starting with `/api/` and should also end with `.json` ```javascript -var proxy = require('http-proxy-middleware'); +const { createProxyMiddleware } = require('http-proxy-middleware'); -var apiProxy = proxy('/api/**/*.json', { target: 'http://localhost:3000' }); +const apiProxy = createProxyMiddleware('/api/**/*.json', { + target: 'http://localhost:3000' +}); ``` ## Multi Wildcard @@ -66,9 +70,9 @@ var apiProxy = proxy('/api/**/*.json', { target: 'http://localhost:3000' }); Multiple wildcards can be used. ```javascript -var proxy = require('http-proxy-middleware'); +const { createProxyMiddleware } = require('http-proxy-middleware'); -var apiProxy = proxy(['/api/**/*.json', '/rest/**'], { +const apiProxy = createProxyMiddleware(['/api/**/*.json', '/rest/**'], { target: 'http://localhost:3000' }); ``` @@ -78,9 +82,9 @@ var apiProxy = proxy(['/api/**/*.json', '/rest/**'], { This example will create a proxy with wildcard context matching. ```javascript -var proxy = require('http-proxy-middleware'); +const { createProxyMiddleware } = require('http-proxy-middleware'); -var apiProxy = proxy(['foo/*.js', '!bar.js'], { +const apiProxy = createProxyMiddleware(['foo/*.js', '!bar.js'], { target: 'http://localhost:3000' }); ``` @@ -91,11 +95,11 @@ Write your custom context matching function to have full control on the matching The request `pathname` and `req` object are provided to determine which requests should be proxied or not. ```javascript -var proxy = require('http-proxy-middleware'); +const { createProxyMiddleware } = require('http-proxy-middleware'); -var filter = function(pathname, req) { +const filter = function(pathname, req) { return pathname.match('^/api') && req.method === 'GET'; }; -var apiProxy = proxy(filter, { target: 'http://localhost:3000' }); +const apiProxy = createProxyMiddleware(filter, { target: 'http://localhost:3000' }); ``` diff --git a/recipes/corporate-proxy.md b/recipes/corporate-proxy.md index 32871171..bbe63f9b 100644 --- a/recipes/corporate-proxy.md +++ b/recipes/corporate-proxy.md @@ -5,16 +5,16 @@ This example will create a basic proxy middleware with corporate proxy support. Provide a custom `http.agent` with [https-proxy-agent](https://github.com/TooTallNate/node-https-proxy-agent) to connect to the corporate proxy server. ```javascript -var HttpsProxyAgent = require('https-proxy-agent'); -var proxy = require('http-proxy-middleware'); +const HttpsProxyAgent = require('https-proxy-agent'); +const { createProxyMiddleware } = require('http-proxy-middleware'); // corporate proxy to connect to -var proxyServer = process.env.HTTPS_PROXY || process.env.HTTP_PROXY; +const proxyServer = process.env.HTTPS_PROXY || process.env.HTTP_PROXY; -var options = { +const options = { target: 'http://localhost:3000', agent: new HttpsProxyAgent(proxyServer) }; -var apiProxy = proxy('/api', options); +const apiProxy = createProxyMiddleware('/api', options); ``` diff --git a/recipes/delay.md b/recipes/delay.md index 3b28f676..3c715c9f 100644 --- a/recipes/delay.md +++ b/recipes/delay.md @@ -8,10 +8,11 @@ Let's assume that we want slow down the access to backend's `/api/get-me-somethi For achieving it just put additional route handler to your app before proxy handler: ```javascript -const myProxy = proxy({ +const myProxy = createProxyMiddleware({ target: 'http://www.example.com', changeOrigin: true }); + const proxyDelay = function(req, res, next) { if (req.originalUrl === '/api/get-me-something') { // Delay request by 2 seconds diff --git a/recipes/https.md b/recipes/https.md index 364c0d55..d4b10eb9 100644 --- a/recipes/https.md +++ b/recipes/https.md @@ -7,9 +7,9 @@ All options are provided by [http-proxy](https://github.com/nodejitsu/node-http- ## Basic proxy to an HTTPS server ```javascript -var proxy = require('http-proxy-middleware'); +const { createProxyMiddleware } = require('http-proxy-middleware'); -var apiProxy = proxy('/api', { +const apiProxy = createProxyMiddleware('/api', { target: 'https://example.org', changeOrigin: true }); @@ -18,10 +18,10 @@ var apiProxy = proxy('/api', { ## Proxy to an HTTPS server using a PKCS12 client certificate ```javascript -var fs = require('fs'); -var proxy = require('http-proxy-middleware'); +const fs = require('fs'); +const { createProxyMiddleware } = require('http-proxy-middleware'); -var apiProxy = proxy('/api', { +const apiProxy = createProxyMiddleware('/api', { target: { protocol: 'https:', host: 'example.org', diff --git a/recipes/logLevel.md b/recipes/logLevel.md index f871639f..0fb1b34a 100644 --- a/recipes/logLevel.md +++ b/recipes/logLevel.md @@ -15,14 +15,14 @@ Possible values: Log everyting. ```javascript -var proxy = require('http-proxy-middleware'); +const { createProxyMiddleware } = require('http-proxy-middleware'); -var options = { +const options = { target: 'http://localhost:3000', logLevel: 'debug' }; -var apiProxy = proxy('/api', options); +const apiProxy = createProxyMiddleware('/api', options); ``` ## Level: silent @@ -30,12 +30,12 @@ var apiProxy = proxy('/api', options); Suppress all logging. ```javascript -var proxy = require('http-proxy-middleware'); +const { createProxyMiddleware } = require('http-proxy-middleware'); -var options = { +const options = { target: 'http://localhost:3000', logLevel: 'silent' }; -var apiProxy = proxy('/api', options); +const apiProxy = createProxyMiddleware('/api', options); ``` diff --git a/recipes/logProvider.md b/recipes/logProvider.md index ef47871b..bbc9e47d 100644 --- a/recipes/logProvider.md +++ b/recipes/logProvider.md @@ -5,17 +5,17 @@ Configure your own logger with the `logProvider` option. In this example [winston](https://www.npmjs.com/package/winston) is configured to do the actual logging. ```javascript -var winston = require('winston'); -var proxy = require('http-proxy-middleware'); +const winston = require('winston'); +const { createProxyMiddleware } = require('http-proxy-middleware'); -var options = { +const options = { target: 'http://localhost:3000', logProvider: function(provider) { return winston; } }; -var apiProxy = proxy('/api', options); +const apiProxy = createProxyMiddleware('/api', options); ``` ## Winston @@ -25,10 +25,10 @@ Configure your own logger with the `logProvider` option. In this example [winston](https://www.npmjs.com/package/winston) is configured to do the actual logging. Map the logging api if needed. ```javascript -var winston = require('winston'); -var proxy = require('http-proxy-middleware'); +const winston = require('winston'); +const { createProxyMiddleware } = require('http-proxy-middleware'); -var logProvider = function(provider) { +const logProvider = function(provider) { return { log: winston.log, debug: winston.debug, @@ -38,12 +38,12 @@ var logProvider = function(provider) { }; }; -var options = { +const options = { target: 'http://localhost:3000', logProvider: logProvider }; -var apiProxy = proxy('/api', options); +const apiProxy = createProxyMiddleware('/api', options); ``` # Winston Multi Transport @@ -53,11 +53,11 @@ Configure your own logger with the `logProvider` option. In this example [winston](https://www.npmjs.com/package/winston) is configured to do the actual logging. ```javascript -var winston = require('winston'); -var proxy = require('http-proxy-middleware'); +const winston = require('winston'); +const { createProxyMiddleware } = require('http-proxy-middleware'); -var logProvider = function(provider) { - var logger = new winston.Logger({ +const logProvider = function(provider) { + const logger = new winston.Logger({ transports: [ new winston.transports.Console(), new winston.transports.File({ filename: 'somefile.log' }) @@ -67,10 +67,10 @@ var logProvider = function(provider) { return logger; }; -var options = { +const options = { target: 'http://localhost:3000', logProvider: logProvider }; -var apiProxy = proxy('/api', options); +const apiProxy = createProxyMiddleware('/api', options); ``` diff --git a/recipes/modify-post.md b/recipes/modify-post.md index 3dc476bb..4966f553 100644 --- a/recipes/modify-post.md +++ b/recipes/modify-post.md @@ -12,17 +12,15 @@ Since this only modifies the request body stream the original POST body paramete ```js 'use strict'; -var express = require('express'); -var ProxyMiddleware = require('http-proxy-middleware'); -var router = express.Router(); - -var proxy_filter = function(path, req) { - return ( - path.match('^/docs') && (req.method === 'GET' || req.method === 'POST') - ); +const express = require('express'); +const { createProxyMiddleware } = require('http-proxy-middleware'); +const router = express.Router(); + +const proxy_filter = function(path, req) { + return path.match('^/docs') && (req.method === 'GET' || req.method === 'POST'); }; -var proxy_options = { +const proxy_options = { target: 'http://localhost:8080', pathRewrite: { '^/docs': '/java/rep/server1' // Host path & target path conversion @@ -31,9 +29,7 @@ var proxy_options = { res.writeHead(500, { 'Content-Type': 'text/plain' }); - res.end( - 'Something went wrong. And we are reporting a custom error message.' + err - ); + res.end('Something went wrong. And we are reporting a custom error message.' + err); }, onProxyReq(proxyReq, req, res) { if (req.method == 'POST' && req.body) { @@ -70,7 +66,7 @@ var proxy_options = { }; // Proxy configuration -var proxy = ProxyMiddleware(proxy_filter, proxy_options); +const proxy = createProxyMiddleware(proxy_filter, proxy_options); /* GET home page. */ router.get('/', function(req, res, next) { diff --git a/recipes/pathRewrite.md b/recipes/pathRewrite.md index fd02deb3..80121a89 100644 --- a/recipes/pathRewrite.md +++ b/recipes/pathRewrite.md @@ -16,16 +16,16 @@ Modify request paths before requests are send to the target. Rewrite paths ```javascript -var proxy = require('http-proxy-middleware'); +const { createProxyMiddleware } = require('http-proxy-middleware'); -var options = { +const options = { target: 'http://localhost:3000', pathRewrite: { '^/api/old-path': '/api/new-path' // rewrite path } }; -var apiProxy = proxy('/api', options); +const apiProxy = createProxyMiddleware('/api', options); // `/old/api/foo/bar` -> `http://localhost:3000/new/api/foo/bar` ``` @@ -35,16 +35,16 @@ var apiProxy = proxy('/api', options); Remove base path ```javascript -var proxy = require('http-proxy-middleware'); +const { createProxyMiddleware } = require('http-proxy-middleware'); -var options = { +const options = { target: 'http://localhost:3000', pathRewrite: { '^/api/': '/' // remove base path } }; -var apiProxy = proxy('/api', options); +const apiProxy = createProxyMiddleware('/api', options); // `/api/lorum/ipsum` -> `http://localhost:3000/lorum/ipsum` ``` @@ -54,16 +54,16 @@ var apiProxy = proxy('/api', options); Add base path ```javascript -var proxy = require('http-proxy-middleware'); +const { createProxyMiddleware } = require('http-proxy-middleware'); -var options = { +const options = { target: 'http://localhost:3000', pathRewrite: { '^/': '/extra/' // add base path } }; -var apiProxy = proxy('/api', options); +const apiProxy = createProxyMiddleware('/api', options); // `/api/lorum/ipsum` -> `http://localhost:3000/extra/api/lorum/ipsum` ``` @@ -75,18 +75,18 @@ Implement you own path rewrite logic. The unmodified path will be used, when rewrite function returns `undefined` ```javascript -var proxy = require('http-proxy-middleware'); +const { createProxyMiddleware } = require('http-proxy-middleware'); -var rewriteFn = function(path, req) { +const rewriteFn = function(path, req) { return path.replace('/api/foo', '/api/bar'); }; -var options = { +const options = { target: 'http://localhost:3000', pathRewrite: rewriteFn }; -var apiProxy = proxy('/api', options); +const apiProxy = createProxyMiddleware('/api', options); // `/api/foo/lorum/ipsum` -> `http://localhost:3000/api/bar/lorum/ipsum` ``` diff --git a/recipes/proxy-events.md b/recipes/proxy-events.md index a1eb67fd..b3a1d93a 100644 --- a/recipes/proxy-events.md +++ b/recipes/proxy-events.md @@ -7,16 +7,16 @@ Subscribe to [`http-proxy`](https://github.com/nodejitsu/node-http-proxy) [![Git Subscribe to http-proxy's [error event](https://www.npmjs.com/package/http-proxy#listening-for-proxy-events). ```javascript -var proxy = require('http-proxy-middleware'); +const { createProxyMiddleware } = require('http-proxy-middleware'); -var onError = function(err, req, res) { +const onError = function(err, req, res) { console.log('Something went wrong.'); console.log('And we are reporting a custom error message.'); }; -var options = { target: 'http://localhost:3000', onError: onError }; +const options = { target: 'http://localhost:3000', onError: onError }; -var apiProxy = proxy('/api', options); +const apiProxy = createProxyMiddleware('/api', options); ``` ## onProxyReq @@ -24,16 +24,16 @@ var apiProxy = proxy('/api', options); Subscribe to http-proxy's [proxyReq event](https://www.npmjs.com/package/http-proxy#listening-for-proxy-events). ```javascript -var proxy = require('http-proxy-middleware'); +const { createProxyMiddleware } = require('http-proxy-middleware'); -var onProxyReq = function(proxyReq, req, res) { +const onProxyReq = function(proxyReq, req, res) { // add new header to request proxyReq.setHeader('x-added', 'foobar'); }; -var options = { target: 'http://localhost:3000', onProxyReq: onProxyReq }; +const options = { target: 'http://localhost:3000', onProxyReq: onProxyReq }; -var apiProxy = proxy('/api', options); +const apiProxy = createProxyMiddleware('/api', options); ``` ## onProxyReqWs @@ -41,16 +41,16 @@ var apiProxy = proxy('/api', options); Subscribe to http-proxy's [proxyReqWs event](https://www.npmjs.com/package/http-proxy#listening-for-proxy-events). ```javascript -var proxy = require('http-proxy-middleware'); +const { createProxyMiddleware } = require('http-proxy-middleware'); -var onProxyReqWs = function(proxyReq, req, socket, options, head) { +const onProxyReqWs = function(proxyReq, req, socket, options, head) { // add custom header proxyReq.setHeader('X-Special-Proxy-Header', 'foobar'); }; -var options = { target: 'http://localhost:3000', onProxyReqWs: onProxyReqWs }; +const options = { target: 'http://localhost:3000', onProxyReqWs: onProxyReqWs }; -var apiProxy = proxy('/api', options); +const apiProxy = createProxyMiddleware('/api', options); ``` ## onProxyRes @@ -58,9 +58,9 @@ var apiProxy = proxy('/api', options); Subscribe to http-proxy's [proxyRes event](https://www.npmjs.com/package/http-proxy#listening-for-proxy-events). ```javascript -var proxy = require('http-proxy-middleware'); +const { createProxyMiddleware } = require('http-proxy-middleware'); -var onProxyRes = function(proxyRes, req, res) { +const onProxyRes = function(proxyRes, req, res) { // add new header to response proxyRes.headers['x-added'] = 'foobar'; @@ -68,7 +68,7 @@ var onProxyRes = function(proxyRes, req, res) { delete proxyRes.headers['x-removed']; }; -var options = { target: 'http://localhost:3000', onProxyRes: onProxyRes }; +const options = { target: 'http://localhost:3000', onProxyRes: onProxyRes }; -var apiProxy = proxy('/api', options); +const apiProxy = createProxyMiddleware('/api', options); ``` diff --git a/recipes/router.md b/recipes/router.md index 923e394c..dc1c11d9 100644 --- a/recipes/router.md +++ b/recipes/router.md @@ -15,21 +15,21 @@ Write your own router to dynamically route to a different `target`. The `req` object is provided to retrieve contextual data. ```javascript -var express = require('express'); -var proxy = require('http-proxy-middleware'); +const express = require('express'); +const { createProxyMiddleware } = require('http-proxy-middleware'); -var customRouter = function(req) { +const customRouter = function(req) { return 'http://www.example.org'; // protocol + host }; -var options = { +const options = { target: 'http://localhost:8000', router: customRouter }; -var myProxy = proxy(options); +const myProxy = createProxyMiddleware(options); -var app = express(); +const app = express(); app.use(myProxy); // add the proxy to express app.listen(3000); @@ -44,24 +44,24 @@ Use a Proxy Table to proxy requests to a different `target` based on: - Host HTTP header + path ```javascript -var express = require('express'); -var proxy = require('http-proxy-middleware'); +const express = require('express'); +const { createProxyMiddleware } = require('http-proxy-middleware'); -var proxyTable = { +const proxyTable = { 'integration.localhost:3000': 'http://localhost:8001', // host only 'staging.localhost:3000': 'http://localhost:8002', // host only 'localhost:3000/api': 'http://localhost:8003', // host + path '/rest': 'http://localhost:8004' // path only }; -var options = { +const options = { target: 'http://localhost:8000', router: proxyTable }; -var myProxy = proxy(options); +const myProxy = createProxyMiddleware(options); -var app = express(); +const app = express(); app.use(myProxy); // add the proxy to express app.listen(3000); diff --git a/recipes/servers.md b/recipes/servers.md index 183bc6e7..1b163d7d 100644 --- a/recipes/servers.md +++ b/recipes/servers.md @@ -24,10 +24,10 @@ https://github.com/BrowserSync/browser-sync [![GitHub stars](https://img.shields.io/github/stars/BrowserSync/browser-sync.svg?style=social&label=Star)](https://github.com/BrowserSync/browser-sync) ```javascript -var browserSync = require('browser-sync').create(); -var proxy = require('http-proxy-middleware'); +const browserSync = require('browser-sync').create(); +const { createProxyMiddleware } = require('http-proxy-middleware'); -var apiProxy = proxy('/api', { +const apiProxy = createProxyMiddleware('/api', { target: 'http://www.example.org', changeOrigin: true // for vhosted sites }); @@ -48,15 +48,15 @@ https://github.com/expressjs/express [![GitHub stars](https://img.shields.io/github/stars/expressjs/express.svg?style=social&label=Star)](https://github.com/expressjs/express) ```javascript -var express = require('express'); -var proxy = require('http-proxy-middleware'); +const express = require('express'); +const { createProxyMiddleware } = require('http-proxy-middleware'); -var apiProxy = proxy('/api', { +const apiProxy = createProxyMiddleware('/api', { target: 'http://www.example.org', changeOrigin: true // for vhosted sites }); -var app = express(); +const app = express(); app.use(apiProxy); app.listen(3000); @@ -68,16 +68,16 @@ https://github.com/senchalabs/connect [![GitHub stars](https://img.shields.io/github/stars/senchalabs/connect.svg?style=social&label=Star)](https://github.com/senchalabs/connect) ```javascript -var http = require('http'); -var connect = require('connect'); -var proxy = require('http-proxy-middleware'); +const http = require('http'); +const connect = require('connect'); +const { createProxyMiddleware } = require('http-proxy-middleware'); -var apiProxy = proxy('/api', { +const apiProxy = createProxyMiddleware('/api', { target: 'http://www.example.org', changeOrigin: true // for vhosted sites }); -var app = connect(); +const app = connect(); app.use(apiProxy); http.createServer(app).listen(3000); @@ -91,9 +91,9 @@ https://github.com/johnpapa/lite-server File: `bs-config.js` ```javascript -var proxy = require('http-proxy-middleware'); +const { createProxyMiddleware } = require('http-proxy-middleware'); -var apiProxy = proxy('/api', { +const apiProxy = createProxyMiddleware('/api', { target: 'http://www.example.org', changeOrigin: true // for vhosted sites }); @@ -117,12 +117,12 @@ https://github.com/lukeed/polka ```javascript const polka = require('polka'); -const proxy = require('http-proxy-middleware'); +const { createProxyMiddleware } = require('http-proxy-middleware'); const app = polka(); app.use( - proxy({ + createProxyMiddleware({ target: 'http://www.example.org', changeOrigin: true }) @@ -139,9 +139,9 @@ https://github.com/gruntjs/grunt-contrib-connect As an `Array`: ```javascript -var proxy = require('http-proxy-middleware'); +const { createProxyMiddleware } = require('http-proxy-middleware'); -var apiProxy = proxy('/api', { +const apiProxy = createProxyMiddleware('/api', { target: 'http://www.example.org', changeOrigin: true // for vhosted sites }); @@ -160,9 +160,9 @@ grunt.initConfig({ As a `function`: ```javascript -var proxy = require('http-proxy-middleware'); +const { createProxyMiddleware } = require('http-proxy-middleware'); -var apiProxy = proxy('/api', { +const apiProxy = createProxyMiddleware('/api', { target: 'http://www.example.org', changeOrigin: true // for vhosted sites }); @@ -189,9 +189,9 @@ https://github.com/BrowserSync/grunt-browser-sync [![GitHub stars](https://img.shields.io/github/stars/BrowserSync/grunt-browser-sync.svg?style=social&label=Star)](https://github.com/BrowserSync/grunt-browser-sync) ```javascript -var proxy = require('http-proxy-middleware'); +const { createProxyMiddleware } = require('http-proxy-middleware'); -var apiProxy = proxy('/api', { +const apiProxy = createProxyMiddleware('/api', { target: 'http://www.example.org', changeOrigin: true // for vhosted sites }); @@ -219,15 +219,15 @@ https://github.com/avevlad/gulp-connect [![GitHub stars](https://img.shields.io/github/stars/avevlad/gulp-connect.svg?style=social&label=Star)](https://github.com/avevlad/gulp-connect) ```javascript -var gulp = require('gulp'); -var connect = require('gulp-connect'); -var proxy = require('http-proxy-middleware'); +const gulp = require('gulp'); +const connect = require('gulp-connect'); +const { createProxyMiddleware } = require('http-proxy-middleware'); gulp.task('connect', function() { connect.server({ root: ['./app'], middleware: function(connect, opt) { - var apiProxy = proxy('/api', { + const apiProxy = createProxyMiddleware('/api', { target: 'http://www.example.org', changeOrigin: true // for vhosted sites }); @@ -246,12 +246,12 @@ https://github.com/schickling/gulp-webserver [![GitHub stars](https://img.shields.io/github/stars/schickling/gulp-webserver.svg?style=social&label=Star)](https://github.com/schickling/gulp-webserver) ```javascript -var gulp = require('gulp'); -var webserver = require('gulp-webserver'); -var proxy = require('http-proxy-middleware'); +const gulp = require('gulp'); +const webserver = require('gulp-webserver'); +const { createProxyMiddleware } = require('http-proxy-middleware'); gulp.task('webserver', function() { - var apiProxy = proxy('/api', { + const apiProxy = createProxyMiddleware('/api', { target: 'http://www.example.org', changeOrigin: true // for vhosted sites }); diff --git a/recipes/shorthand.md b/recipes/shorthand.md index 2baee000..30ca8b7f 100644 --- a/recipes/shorthand.md +++ b/recipes/shorthand.md @@ -5,12 +5,12 @@ This example will create a proxy middleware using the shorthand notation. The http-proxy-middleware `context` and `config.target` will be set automatically. ```javascript -var proxy = require('http-proxy-middleware'); +const { createProxyMiddleware } = require('http-proxy-middleware'); -var apiProxy = proxy('http://localhost:3000/api'); +const apiProxy = createProxyMiddleware('http://localhost:3000/api'); // equivalent: -// var apiProxy = proxy('/api', {target:'http://localhost:3000'}); +// const apiProxy = createProxyMiddleware('/api', {target:'http://localhost:3000'}); ``` ## Shorthand - Wildcard context @@ -18,11 +18,11 @@ var apiProxy = proxy('http://localhost:3000/api'); This example will create a proxy middleware with shorthand wildcard context. ```javascript -var proxy = require('http-proxy-middleware'); +const { createProxyMiddleware } = require('http-proxy-middleware'); -var apiProxy = proxy('http://localhost:3000/api/books/*/**.json'); +const apiProxy = createProxyMiddleware('http://localhost:3000/api/books/*/**.json'); // equals: -// var apiProxy = proxy('/api/books/*/**.json', {target:'http://localhost:3000'}); +// const apiProxy = createProxyMiddleware('/api/books/*/**.json', {target:'http://localhost:3000'}); ``` ## Shorthand with additional configuration @@ -30,11 +30,11 @@ var apiProxy = proxy('http://localhost:3000/api/books/*/**.json'); This example will create a proxy middleware with shorthand and additional configuration. ```javascript -var proxy = require('http-proxy-middleware'); +const { createProxyMiddleware } = require('http-proxy-middleware'); -var apiProxy = proxy('http://localhost:3000/api', { changeOrigin: true }); +const apiProxy = createProxyMiddleware('http://localhost:3000/api', { changeOrigin: true }); // equals: -// var apiProxy = proxy('/api', {target:'http://localhost:3000', {changeOrigin:true}}); +// const apiProxy = createProxyMiddleware('/api', {target:'http://localhost:3000', {changeOrigin:true}}); ``` ## Shorthand - WebSocket @@ -42,11 +42,11 @@ var apiProxy = proxy('http://localhost:3000/api', { changeOrigin: true }); This example will create a proxy middleware with shorthand and additional configuration for WebSocket support. ```javascript -var proxy = require('http-proxy-middleware'); +const { createProxyMiddleware } = require('http-proxy-middleware'); -var apiProxy = proxy('http://localhost:3000/api', { ws: true }); +const apiProxy = createProxyMiddleware('http://localhost:3000/api', { ws: true }); // equals: -// var apiProxy = proxy('/api', {target:'http://localhost:3000', ws: true}); +// const apiProxy = createProxyMiddleware('/api', {target:'http://localhost:3000', ws: true}); ``` ## Shorthand - WebSocket only @@ -54,9 +54,9 @@ var apiProxy = proxy('http://localhost:3000/api', { ws: true }); This example will create a proxy middleware with websocket shorthand only configuration. ```javascript -var proxy = require('http-proxy-middleware'); +const { createProxyMiddleware } = require('http-proxy-middleware'); -var apiProxy = proxy('ws://localhost:3000/api'); +const apiProxy = createProxyMiddleware('ws://localhost:3000/api'); // equals: -// var apiProxy = proxy('/api', {target:'ws://localhost:3000', ws: true}); +// const apiProxy = createProxyMiddleware('/api', {target:'ws://localhost:3000', ws: true}); ``` diff --git a/recipes/virtual-hosts.md b/recipes/virtual-hosts.md index 25e47219..b83d0135 100644 --- a/recipes/virtual-hosts.md +++ b/recipes/virtual-hosts.md @@ -7,12 +7,12 @@ When `changeOrigin` is set to `true`; Host [HTTP header](https://en.wikipedia.or The `changeOrigin` option is provided by [http-proxy](https://github.com/nodejitsu/node-http-proxy). ```javascript -var proxy = require('http-proxy-middleware'); +const { createProxyMiddleware } = require('http-proxy-middleware'); -var options = { +const options = { target: 'http://localhost:3000', changeOrigin: true }; -var apiProxy = proxy('/api', options); +const apiProxy = createProxyMiddleware('/api', options); ``` diff --git a/recipes/websocket.md b/recipes/websocket.md index 8bc73953..d4317a95 100644 --- a/recipes/websocket.md +++ b/recipes/websocket.md @@ -3,9 +3,9 @@ This example will create a proxy middleware with websocket support. ```javascript -var proxy = require('http-proxy-middleware'); +const { createProxyMiddleware } = require('http-proxy-middleware'); -var socketProxy = proxy('/socket', { +const socketProxy = createProxyMiddleware('/socket', { target: 'http://localhost:3000', ws: true }); @@ -16,9 +16,9 @@ var socketProxy = proxy('/socket', { This example will create a proxy middleware with websocket support and pathRewrite. ```javascript -var proxy = require('http-proxy-middleware'); +const { createProxyMiddleware } = require('http-proxy-middleware'); -var options = { +const options = { target: 'http://localhost:3000', ws: true, pathRewrite: { @@ -26,7 +26,7 @@ var options = { } }; -var socketProxy = proxy('/socket', options); +const socketProxy = createProxyMiddleware('/socket', options); ``` ## WebSocket - Server update subscription @@ -36,9 +36,9 @@ This example will create a proxy middleware with websocket support. Subscribe to server's upgrade event. ```javascript -var proxy = require('http-proxy-middleware'); +const { createProxyMiddleware } = require('http-proxy-middleware'); -var socketProxy = proxy('/socket', { +const socketProxy = createProxyMiddleware('/socket', { target: 'http://localhost:3000', ws: true }); diff --git a/src/config-factory.ts b/src/config-factory.ts index 6dfe632d..a54076be 100644 --- a/src/config-factory.ts +++ b/src/config-factory.ts @@ -1,5 +1,5 @@ -import _ from 'lodash'; -import url from 'url'; +import * as _ from 'lodash'; +import * as url from 'url'; import { ERRORS } from './errors'; import { getInstance } from './logger'; import { Filter, Options } from './types'; diff --git a/src/context-matcher.ts b/src/context-matcher.ts index a2173a97..f04f9365 100644 --- a/src/context-matcher.ts +++ b/src/context-matcher.ts @@ -1,7 +1,7 @@ -import isGlob from 'is-glob'; -import _ from 'lodash'; -import micromatch from 'micromatch'; -import url from 'url'; +import * as isGlob from 'is-glob'; +import * as _ from 'lodash'; +import * as micromatch from 'micromatch'; +import * as url from 'url'; import { ERRORS } from './errors'; export function match(context, uri, req) { diff --git a/src/handlers.ts b/src/handlers.ts index db441e20..344c7eaa 100644 --- a/src/handlers.ts +++ b/src/handlers.ts @@ -1,4 +1,4 @@ -import _ from 'lodash'; +import * as _ from 'lodash'; import { getInstance } from './logger'; const logger = getInstance(); @@ -14,14 +14,7 @@ export function init(proxy, option) { export function getHandlers(options) { // https://github.com/nodejitsu/node-http-proxy#listening-for-proxy-events - const proxyEvents = [ - 'error', - 'proxyReq', - 'proxyReqWs', - 'proxyRes', - 'open', - 'close' - ]; + const proxyEvents = ['error', 'proxyReq', 'proxyReqWs', 'proxyRes', 'open', 'close']; const handlers: any = {}; for (const event of proxyEvents) { diff --git a/src/http-proxy-middleware.ts b/src/http-proxy-middleware.ts index c6fe7598..2874b6f1 100644 --- a/src/http-proxy-middleware.ts +++ b/src/http-proxy-middleware.ts @@ -1,13 +1,13 @@ -import express from 'express'; -import httpProxy from 'http-proxy'; -import _ from 'lodash'; +import * as express from 'express'; +import * as httpProxy from 'http-proxy'; +import * as _ from 'lodash'; import { createConfig } from './config-factory'; import * as contextMatcher from './context-matcher'; import * as handlers from './handlers'; import { getArrow, getInstance } from './logger'; import * as PathRewriter from './path-rewriter'; import * as Router from './router'; -import { Filter, IRequest, IRequestHandler, IResponse, Options } from './types'; +import { Filter, Request, RequestHandler, Response, Options } from './types'; export class HttpProxyMiddleware { private logger = getInstance(); @@ -23,13 +23,9 @@ export class HttpProxyMiddleware { // create proxy this.proxy = httpProxy.createProxyServer({}); - this.logger.info( - `[HPM] Proxy created: ${this.config.context} -> ${this.proxyOptions.target}` - ); + this.logger.info(`[HPM] Proxy created: ${this.config.context} -> ${this.proxyOptions.target}`); - this.pathRewriter = PathRewriter.createPathRewriter( - this.proxyOptions.pathRewrite - ); // returns undefined when "pathRewrite" is not provided + this.pathRewriter = PathRewriter.createPathRewriter(this.proxyOptions.pathRewrite); // returns undefined when "pathRewrite" is not provided // attach handler to http-proxy events handlers.init(this.proxy, this.proxyOptions); @@ -47,9 +43,9 @@ export class HttpProxyMiddleware { } // https://github.com/Microsoft/TypeScript/wiki/'this'-in-TypeScript#red-flags-for-this - public middleware: IRequestHandler = async ( - req: IRequest, - res: IResponse, + public middleware: RequestHandler = async ( + req: Request, + res: Response, next: express.NextFunction ) => { if (this.shouldProxy(this.config.context, req)) { @@ -74,7 +70,7 @@ export class HttpProxyMiddleware { } }; - private handleUpgrade = async (req: IRequest, socket, head) => { + private handleUpgrade = async (req: Request, socket, head) => { if (this.shouldProxy(this.config.context, req)) { const activeProxyOptions = await this.prepareProxyRequest(req); this.proxy.ws(req, socket, head, activeProxyOptions); @@ -90,7 +86,7 @@ export class HttpProxyMiddleware { * @param {Object} req [description] * @return {Boolean} */ - private shouldProxy = (context, req: IRequest) => { + private shouldProxy = (context, req: Request) => { const path = req.originalUrl || req.url; return contextMatcher.match(context, path, req); }; @@ -103,7 +99,7 @@ export class HttpProxyMiddleware { * @param {Object} req * @return {Object} proxy options */ - private prepareProxyRequest = async (req: IRequest) => { + private prepareProxyRequest = async (req: Request) => { // https://github.com/chimurai/http-proxy-middleware/issues/17 // https://github.com/chimurai/http-proxy-middleware/issues/94 req.url = req.originalUrl || req.url; @@ -139,56 +135,39 @@ export class HttpProxyMiddleware { }; // Modify option.target when router present. - private applyRouter = async (req: IRequest, options) => { + private applyRouter = async (req: Request, options) => { let newTarget; if (options.router) { newTarget = await Router.getTarget(req, options); if (newTarget) { - this.logger.debug( - '[HPM] Router new target: %s -> "%s"', - options.target, - newTarget - ); + this.logger.debug('[HPM] Router new target: %s -> "%s"', options.target, newTarget); options.target = newTarget; } } }; // rewrite path - private applyPathRewrite = async (req: IRequest, pathRewriter) => { + private applyPathRewrite = async (req: Request, pathRewriter) => { if (pathRewriter) { const path = await pathRewriter(req.url, req); if (typeof path === 'string') { req.url = path; } else { - this.logger.info( - '[HPM] pathRewrite: No rewritten path found. (%s)', - req.url - ); + this.logger.info('[HPM] pathRewrite: No rewritten path found. (%s)', req.url); } } }; - private logError = (err, req: IRequest, res: IResponse) => { - const hostname = - (req.headers && req.headers.host) || req.hostname || req.host; // (websocket) || (node0.10 || node 4/5) - const target = - (this.proxyOptions.target as any).host || this.proxyOptions.target; + private logError = (err, req: Request, res: Response) => { + const hostname = (req.headers && req.headers.host) || req.hostname || req.host; // (websocket) || (node0.10 || node 4/5) + const target = (this.proxyOptions.target as any).host || this.proxyOptions.target; const errorMessage = '[HPM] Error occurred while trying to proxy request %s from %s to %s (%s) (%s)'; - const errReference = - 'https://nodejs.org/api/errors.html#errors_common_system_errors'; // link to Node Common Systems Errors page - - this.logger.error( - errorMessage, - req.url, - hostname, - target, - err.code || err, - errReference - ); + const errReference = 'https://nodejs.org/api/errors.html#errors_common_system_errors'; // link to Node Common Systems Errors page + + this.logger.error(errorMessage, req.url, hostname, target, err.code || err, errReference); }; } diff --git a/src/index.ts b/src/index.ts index d4ec7d66..9e421cd6 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,9 +1,9 @@ import { HttpProxyMiddleware } from './http-proxy-middleware'; import { Filter, Options } from './types'; -function middleware(context: Filter | Options, options?: Options) { +export function createProxyMiddleware(context: Filter | Options, options?: Options) { const { middleware } = new HttpProxyMiddleware(context, options); return middleware; } -export = middleware; +export { Filter, Options, RequestHandler } from './types'; diff --git a/src/logger.ts b/src/logger.ts index 50aece48..6f7f381d 100644 --- a/src/logger.ts +++ b/src/logger.ts @@ -1,5 +1,5 @@ -import _ from 'lodash'; -import util from 'util'; +import * as _ from 'lodash'; +import * as util from 'util'; let loggerInstance; diff --git a/src/path-rewriter.ts b/src/path-rewriter.ts index 160a7f6d..f451594d 100644 --- a/src/path-rewriter.ts +++ b/src/path-rewriter.ts @@ -1,4 +1,4 @@ -import _ from 'lodash'; +import * as _ from 'lodash'; import { ERRORS } from './errors'; import { getInstance } from './logger'; const logger = getInstance(); @@ -64,11 +64,7 @@ function parsePathRewriteRules(rewriteConfig) { regex: new RegExp(key), value: rewriteConfig[key] }); - logger.info( - '[HPM] Proxy rewrite rule created: "%s" ~> "%s"', - key, - rewriteConfig[key] - ); + logger.info('[HPM] Proxy rewrite rule created: "%s" ~> "%s"', key, rewriteConfig[key]); }); } diff --git a/src/router.ts b/src/router.ts index fcee4dcf..37200b94 100644 --- a/src/router.ts +++ b/src/router.ts @@ -1,4 +1,4 @@ -import _ from 'lodash'; +import * as _ from 'lodash'; import { getInstance } from './logger'; const logger = getInstance(); diff --git a/src/types.ts b/src/types.ts index 06ff4f1d..d735606c 100644 --- a/src/types.ts +++ b/src/types.ts @@ -1,52 +1,41 @@ -import express from 'express'; -import http from 'http'; -import httpProxy from 'http-proxy'; -import net from 'net'; +import * as express from 'express'; +import * as http from 'http'; +import * as httpProxy from 'http-proxy'; +import * as net from 'net'; -export interface IRequest extends express.Request {} -export interface IResponse extends express.Response {} +export interface Request extends express.Request {} +export interface Response extends express.Response {} -export interface IRequestHandler extends express.RequestHandler { - upgrade?: (req: IRequest, socket: net.Socket, head: any) => void; +export interface RequestHandler extends express.RequestHandler { + upgrade?: (req: Request, socket: net.Socket, head: any) => void; } -export type Filter = - | string - | string[] - | ((pathname: string, req: IRequest) => boolean); +export type Filter = string | string[] | ((pathname: string, req: Request) => boolean); export interface Options extends httpProxy.ServerOptions { pathRewrite?: | { [regexp: string]: string } - | ((path: string, req: IRequest) => string) - | ((path: string, req: IRequest) => Promise); + | ((path: string, req: Request) => string) + | ((path: string, req: Request) => Promise); router?: | { [hostOrPath: string]: string } - | ((req: IRequest) => string) - | ((req: IRequest) => Promise); + | ((req: Request) => string) + | ((req: Request) => Promise); logLevel?: 'debug' | 'info' | 'warn' | 'error' | 'silent'; logProvider?(provider: LogProvider): LogProvider; - onError?(err: Error, req: IRequest, res: IResponse): void; - onProxyRes?( - proxyRes: http.ServerResponse, - req: IRequest, - res: IResponse - ): void; - onProxyReq?( - proxyReq: http.ClientRequest, - req: IRequest, - res: IResponse - ): void; + onError?(err: Error, req: Request, res: Response): void; + onProxyRes?(proxyRes: http.ServerResponse, req: Request, res: Response): void; + onProxyReq?(proxyReq: http.ClientRequest, req: Request, res: Response): void; onProxyReqWs?( proxyReq: http.ClientRequest, - req: IRequest, + req: Request, socket: net.Socket, options: httpProxy.ServerOptions, head: any ): void; onOpen?(proxySocket: net.Socket): void; - onClose?(res: IResponse, socket: net.Socket, head: any): void; + onClose?(res: Response, socket: net.Socket, head: any): void; } interface LogProvider { diff --git a/test/e2e/_utils.ts b/test/e2e/_utils.ts index d3e92416..f47a2371 100644 --- a/test/e2e/_utils.ts +++ b/test/e2e/_utils.ts @@ -1,7 +1,6 @@ -import express from 'express'; +import * as express from 'express'; -// tslint:disable-next-line: no-var-requires -export const proxyMiddleware = require('../../dist/index'); +export { createProxyMiddleware } from '../../dist/index'; export function createServer(portNumber, middleware, path?) { const app = express(); diff --git a/test/e2e/express-router.spec.ts b/test/e2e/express-router.spec.ts index 3913981d..a643aa7d 100644 --- a/test/e2e/express-router.spec.ts +++ b/test/e2e/express-router.spec.ts @@ -1,6 +1,7 @@ -import express from 'express'; -import http from 'http'; -import { proxyMiddleware as proxy } from './_utils'; +import * as express from 'express'; +import * as http from 'http'; +import { createProxyMiddleware } from './_utils'; +import { Options } from '../../src/index'; describe('Usage in Express', () => { let app; @@ -31,12 +32,12 @@ describe('Usage in Express', () => { /** * Mount proxy without 'path' in sub route */ - const proxyConfig = { + const proxyConfig: Options = { changeOrigin: true, logLevel: 'silent', target: 'http://jsonplaceholder.typicode.com' }; - sub.use(proxy(filter, proxyConfig)); + sub.use(createProxyMiddleware(filter, proxyConfig)); sub.get('/hello', jsonMiddleware({ content: 'foobar' })); diff --git a/test/e2e/http-proxy-middleware.spec.ts b/test/e2e/http-proxy-middleware.spec.ts index 3211f79c..88517da9 100644 --- a/test/e2e/http-proxy-middleware.spec.ts +++ b/test/e2e/http-proxy-middleware.spec.ts @@ -1,11 +1,11 @@ -import http from 'http'; -import { createServer, proxyMiddleware } from './_utils'; +import * as http from 'http'; +import { createServer, createProxyMiddleware } from './_utils'; describe('E2E http-proxy-middleware', () => { describe('http-proxy-middleware creation', () => { it('should create a middleware', () => { let middleware; - middleware = proxyMiddleware('/api', { + middleware = createProxyMiddleware('/api', { target: 'http://localhost:8000' }); expect(typeof middleware).toBe('function'); @@ -28,7 +28,7 @@ describe('E2E http-proxy-middleware', () => { isSkipped = true; }; - middleware = proxyMiddleware('/api', { + middleware = createProxyMiddleware('/api', { target: 'http://localhost:8000' }); middleware(mockReq, mockRes, mockNext); @@ -49,7 +49,7 @@ describe('E2E http-proxy-middleware', () => { let responseBody; beforeEach(done => { - const mwProxy = proxyMiddleware('/api', { + const mwProxy = createProxyMiddleware('/api', { target: 'http://localhost:8000' }); @@ -104,7 +104,7 @@ describe('E2E http-proxy-middleware', () => { return true; }; - const mwProxy = proxyMiddleware(filter, { + const mwProxy = createProxyMiddleware(filter, { target: 'http://localhost:8000' }); @@ -149,7 +149,7 @@ describe('E2E http-proxy-middleware', () => { let responseBody; beforeEach(() => { - const mwProxy = proxyMiddleware(['/api', '/ajax'], { + const mwProxy = createProxyMiddleware(['/api', '/ajax'], { target: 'http://localhost:8000' }); @@ -225,7 +225,7 @@ describe('E2E http-proxy-middleware', () => { let responseBody; beforeEach(() => { - const mwProxy = proxyMiddleware('/api/**', { + const mwProxy = createProxyMiddleware('/api/**', { target: 'http://localhost:8000' }); @@ -267,7 +267,7 @@ describe('E2E http-proxy-middleware', () => { let responseB; beforeEach(() => { - const mwProxy = proxyMiddleware(['**/*.html', '!**.json'], { + const mwProxy = createProxyMiddleware(['**/*.html', '!**.json'], { target: 'http://localhost:8000' }); @@ -320,7 +320,7 @@ describe('E2E http-proxy-middleware', () => { let targetHeaders; beforeEach(done => { - const mwProxy = proxyMiddleware('/api', { + const mwProxy = createProxyMiddleware('/api', { target: 'http://localhost:8000', headers: { host: 'foobar.dev' } }); @@ -356,7 +356,7 @@ describe('E2E http-proxy-middleware', () => { describe('default', () => { beforeEach(done => { - const mwProxy = proxyMiddleware('/api', { + const mwProxy = createProxyMiddleware('/api', { target: 'http://localhost:666' }); // unreachable host on port:666 const mwTarget = (req, res, next) => { @@ -391,7 +391,7 @@ describe('E2E http-proxy-middleware', () => { } }; - const mwProxy = proxyMiddleware('/api', { + const mwProxy = createProxyMiddleware('/api', { target: 'http://localhost:666', onError: customOnError }); // unreachable host on port:666 @@ -437,7 +437,7 @@ describe('E2E http-proxy-middleware', () => { delete proxyRes.headers['x-removed']; }; - const mwProxy = proxyMiddleware('/api', { + const mwProxy = createProxyMiddleware('/api', { target: 'http://localhost:8000', onProxyRes: fnOnProxyRes }); @@ -482,7 +482,7 @@ describe('E2E http-proxy-middleware', () => { proxyReq.setHeader('x-added', 'foobar'); // add custom header to request }; - const mwProxy = proxyMiddleware('/api', { + const mwProxy = createProxyMiddleware('/api', { target: 'http://localhost:8000', onProxyReq: fnOnProxyReq }); @@ -517,7 +517,7 @@ describe('E2E http-proxy-middleware', () => { let responseBody; beforeEach(done => { - const mwProxy = proxyMiddleware('/api', { + const mwProxy = createProxyMiddleware('/api', { target: 'http://localhost:8000', pathRewrite: { '^/api': '/rest', @@ -556,7 +556,7 @@ describe('E2E http-proxy-middleware', () => { let responseBody; beforeEach(done => { - const mwProxy = proxyMiddleware('http://localhost:8000/api'); + const mwProxy = createProxyMiddleware('http://localhost:8000/api'); const mwTarget = (req, res, next) => { res.write(req.url); // respond with req.url res.end(); @@ -589,7 +589,7 @@ describe('E2E http-proxy-middleware', () => { let responseBody; beforeEach(done => { - const mwProxy = proxyMiddleware('http://localhost:8000'); + const mwProxy = createProxyMiddleware('http://localhost:8000'); const mwTarget = (req, res, next) => { res.write(req.url); // respond with req.url res.end(); @@ -626,7 +626,7 @@ describe('E2E http-proxy-middleware', () => { logMessage = message; }; - const mwProxy = proxyMiddleware('http://localhost:8000/api', { + const mwProxy = createProxyMiddleware('http://localhost:8000/api', { logLevel: 'info', logProvider(provider) { provider.debug = customLogger; diff --git a/test/e2e/path-rewriter.spec.ts b/test/e2e/path-rewriter.spec.ts index 4699ae0b..fc33ae98 100644 --- a/test/e2e/path-rewriter.spec.ts +++ b/test/e2e/path-rewriter.spec.ts @@ -1,5 +1,5 @@ -import http from 'http'; -import { createServer, proxyMiddleware } from './_utils'; +import * as http from 'http'; +import { createServer, createProxyMiddleware } from './_utils'; describe('E2E pathRewrite', () => { let targetMiddleware; @@ -36,7 +36,7 @@ describe('E2E pathRewrite', () => { '^/foobar/api/': '/api/' } }; - const proxy = proxyMiddleware(proxyConfig); + const proxy = createProxyMiddleware(proxyConfig); proxyServer = createServer(3000, proxy); }); @@ -64,7 +64,7 @@ describe('E2E pathRewrite', () => { return path.replace('/foobar', ''); } }; - const proxy = proxyMiddleware(proxyConfig); + const proxy = createProxyMiddleware(proxyConfig); proxyServer = createServer(3000, proxy); }); diff --git a/test/e2e/router.spec.ts b/test/e2e/router.spec.ts index bd89e5a7..a89f0ebd 100644 --- a/test/e2e/router.spec.ts +++ b/test/e2e/router.spec.ts @@ -1,5 +1,5 @@ -import http from 'http'; -import { createServer, proxyMiddleware } from './_utils'; +import * as http from 'http'; +import { createServer, createProxyMiddleware } from './_utils'; describe('E2E router', () => { let proxyServer; @@ -34,7 +34,7 @@ describe('E2E router', () => { beforeEach(() => { proxyServer = createServer( 6000, - proxyMiddleware({ + createProxyMiddleware({ target: 'http://localhost:6001', router(req) { return 'http://localhost:6003'; @@ -63,7 +63,7 @@ describe('E2E router', () => { beforeEach(function setupServers() { proxyServer = createServer( 6000, - proxyMiddleware('/', { + createProxyMiddleware('/', { target: 'http://localhost:6001', router: { 'alpha.localhost:6000': 'http://localhost:6001', diff --git a/test/e2e/websocket.spec.ts b/test/e2e/websocket.spec.ts index 53fce0a9..c52d9b09 100644 --- a/test/e2e/websocket.spec.ts +++ b/test/e2e/websocket.spec.ts @@ -1,8 +1,8 @@ -import http from 'http'; -import WebSocket from 'ws'; +import * as http from 'http'; +import * as WebSocket from 'ws'; // tslint:disable-next-line: no-duplicate-imports import { Server as WebSocketServer } from 'ws'; -import { createServer, proxyMiddleware } from './_utils'; +import { createServer, createProxyMiddleware } from './_utils'; describe('E2E WebSocket proxy', () => { let proxyServer; @@ -12,7 +12,7 @@ describe('E2E WebSocket proxy', () => { let proxy; beforeEach(() => { - proxy = proxyMiddleware('/', { + proxy = createProxyMiddleware('/', { target: 'http://localhost:8000', ws: true, pathRewrite: { '^/socket': '' } @@ -84,7 +84,7 @@ describe('E2E WebSocket proxy', () => { beforeEach(() => { proxyServer.close(); // override - proxy = proxyMiddleware('ws://localhost:8000', { + proxy = createProxyMiddleware('ws://localhost:8000', { pathRewrite: { '^/socket': '' } }); proxyServer = createServer(3000, proxy); @@ -115,7 +115,7 @@ describe('E2E WebSocket proxy', () => { beforeEach(() => { proxyServer.close(); // override - proxy = proxyMiddleware('ws://notworkinghost:6789', { + proxy = createProxyMiddleware('ws://notworkinghost:6789', { router: { '/socket': 'ws://localhost:8000' }, pathRewrite: { '^/socket': '' } }); diff --git a/test/types.spec.ts b/test/types.spec.ts index 671ae47e..f6a2bb4f 100644 --- a/test/types.spec.ts +++ b/test/types.spec.ts @@ -1,4 +1,4 @@ -import middleware from '../src'; +import { createProxyMiddleware as middleware } from '../src'; import { Options } from '../src/types'; describe('http-proxy-middleware TypeScript Types', () => { diff --git a/test/unit/context-matcher.spec.ts b/test/unit/context-matcher.spec.ts index a47da6b6..eaf37224 100644 --- a/test/unit/context-matcher.spec.ts +++ b/test/unit/context-matcher.spec.ts @@ -8,94 +8,54 @@ describe('Context Matching', () => { describe('Single path matching', () => { it('should match all paths', () => { - result = contextMatcher.match( - '', - 'http://localhost/api/foo/bar', - fakeReq - ); + result = contextMatcher.match('', 'http://localhost/api/foo/bar', fakeReq); expect(result).toBe(true); }); it('should match all paths starting with forward-slash', () => { - result = contextMatcher.match( - '/', - 'http://localhost/api/foo/bar', - fakeReq - ); + result = contextMatcher.match('/', 'http://localhost/api/foo/bar', fakeReq); expect(result).toBe(true); }); it('should return true when the context is present in url', () => { - result = contextMatcher.match( - '/api', - 'http://localhost/api/foo/bar', - fakeReq - ); + result = contextMatcher.match('/api', 'http://localhost/api/foo/bar', fakeReq); expect(result).toBe(true); }); it('should return false when the context is not present in url', () => { - result = contextMatcher.match( - '/abc', - 'http://localhost/api/foo/bar', - fakeReq - ); + result = contextMatcher.match('/abc', 'http://localhost/api/foo/bar', fakeReq); expect(result).toBe(false); }); it('should return false when the context is present half way in url', () => { - result = contextMatcher.match( - '/foo', - 'http://localhost/api/foo/bar', - fakeReq - ); + result = contextMatcher.match('/foo', 'http://localhost/api/foo/bar', fakeReq); expect(result).toBe(false); }); it('should return false when the context does not start with /', () => { - result = contextMatcher.match( - 'api', - 'http://localhost/api/foo/bar', - fakeReq - ); + result = contextMatcher.match('api', 'http://localhost/api/foo/bar', fakeReq); expect(result).toBe(false); }); }); describe('Multi path matching', () => { it('should return true when the context is present in url', () => { - result = contextMatcher.match( - ['/api'], - 'http://localhost/api/foo/bar', - fakeReq - ); + result = contextMatcher.match(['/api'], 'http://localhost/api/foo/bar', fakeReq); expect(result).toBe(true); }); it('should return true when the context is present in url', () => { - result = contextMatcher.match( - ['/api', '/ajax'], - 'http://localhost/ajax/foo/bar', - fakeReq - ); + result = contextMatcher.match(['/api', '/ajax'], 'http://localhost/ajax/foo/bar', fakeReq); expect(result).toBe(true); }); it('should return false when the context does not match url', () => { - result = contextMatcher.match( - ['/api', '/ajax'], - 'http://localhost/foo/bar', - fakeReq - ); + result = contextMatcher.match(['/api', '/ajax'], 'http://localhost/foo/bar', fakeReq); expect(result).toBe(false); }); it('should return false when empty array provided', () => { - result = contextMatcher.match( - [], - 'http://localhost/api/foo/bar', - fakeReq - ); + result = contextMatcher.match([], 'http://localhost/api/foo/bar', fakeReq); expect(result).toBe(false); }); }); @@ -122,9 +82,7 @@ describe('Context Matching', () => { it('should only match paths starting with "foo" folder in it ', () => { expect(contextMatcher.match('**/foo/**', url, fakeReq)).toBe(true); - expect(contextMatcher.match('**/invalid/**', url, fakeReq)).toBe( - false - ); + expect(contextMatcher.match('**/invalid/**', url, fakeReq)).toBe(false); }); }); @@ -147,75 +105,37 @@ describe('Context Matching', () => { it('should only match .html under root path', () => { const pattern = '/*.html'; + expect(contextMatcher.match(pattern, 'http://localhost/index.html', fakeReq)).toBe(true); expect( - contextMatcher.match( - pattern, - 'http://localhost/index.html', - fakeReq - ) - ).toBe(true); - expect( - contextMatcher.match( - pattern, - 'http://localhost/some/path/index.html', - fakeReq - ) + contextMatcher.match(pattern, 'http://localhost/some/path/index.html', fakeReq) ).toBe(false); }); it('should ignore query params', () => { expect( - contextMatcher.match( - '/**/*.php', - 'http://localhost/a/b/c.php?d=e&e=f', - fakeReq - ) + contextMatcher.match('/**/*.php', 'http://localhost/a/b/c.php?d=e&e=f', fakeReq) ).toBe(true); expect( - contextMatcher.match( - '/**/*.php?*', - 'http://localhost/a/b/c.php?d=e&e=f', - fakeReq - ) + contextMatcher.match('/**/*.php?*', 'http://localhost/a/b/c.php?d=e&e=f', fakeReq) ).toBe(false); }); it('should only match any file in root path', () => { - expect( - contextMatcher.match('/*', 'http://localhost/bar.html', fakeReq) - ).toBe(true); - expect( - contextMatcher.match('/*.*', 'http://localhost/bar.html', fakeReq) - ).toBe(true); - expect( - contextMatcher.match('/*', 'http://localhost/foo/bar.html', fakeReq) - ).toBe(false); + expect(contextMatcher.match('/*', 'http://localhost/bar.html', fakeReq)).toBe(true); + expect(contextMatcher.match('/*.*', 'http://localhost/bar.html', fakeReq)).toBe(true); + expect(contextMatcher.match('/*', 'http://localhost/foo/bar.html', fakeReq)).toBe(false); }); it('should only match .html file is in root path', () => { + expect(contextMatcher.match('/*.html', 'http://localhost/bar.html', fakeReq)).toBe(true); expect( - contextMatcher.match( - '/*.html', - 'http://localhost/bar.html', - fakeReq - ) - ).toBe(true); - expect( - contextMatcher.match( - '/*.html', - 'http://localhost/api/foo/bar.html', - fakeReq - ) + contextMatcher.match('/*.html', 'http://localhost/api/foo/bar.html', fakeReq) ).toBe(false); }); it('should only match .html files in "foo" folder', () => { - expect(contextMatcher.match('**/foo/*.html', url, fakeReq)).toBe( - true - ); - expect(contextMatcher.match('**/bar/*.html', url, fakeReq)).toBe( - false - ); + expect(contextMatcher.match('**/foo/*.html', url, fakeReq)).toBe(true); + expect(contextMatcher.match('**/bar/*.html', url, fakeReq)).toBe(false); }); it('should not match .html files', () => { @@ -228,63 +148,35 @@ describe('Context Matching', () => { describe('Multiple patterns', () => { it('should return true when both path patterns match', () => { const pattern = ['/api/**', '/ajax/**']; - expect( - contextMatcher.match( - pattern, - 'http://localhost/api/foo/bar.json', - fakeReq - ) - ).toBe(true); - expect( - contextMatcher.match( - pattern, - 'http://localhost/ajax/foo/bar.json', - fakeReq - ) - ).toBe(true); - expect( - contextMatcher.match( - pattern, - 'http://localhost/rest/foo/bar.json', - fakeReq - ) - ).toBe(false); + expect(contextMatcher.match(pattern, 'http://localhost/api/foo/bar.json', fakeReq)).toBe( + true + ); + expect(contextMatcher.match(pattern, 'http://localhost/ajax/foo/bar.json', fakeReq)).toBe( + true + ); + expect(contextMatcher.match(pattern, 'http://localhost/rest/foo/bar.json', fakeReq)).toBe( + false + ); }); it('should return true when both file extensions pattern match', () => { const pattern = ['/**/*.html', '/**/*.jpeg']; - expect( - contextMatcher.match( - pattern, - 'http://localhost/api/foo/bar.html', - fakeReq - ) - ).toBe(true); - expect( - contextMatcher.match( - pattern, - 'http://localhost/api/foo/bar.jpeg', - fakeReq - ) - ).toBe(true); - expect( - contextMatcher.match( - pattern, - 'http://localhost/api/foo/bar.gif', - fakeReq - ) - ).toBe(false); + expect(contextMatcher.match(pattern, 'http://localhost/api/foo/bar.html', fakeReq)).toBe( + true + ); + expect(contextMatcher.match(pattern, 'http://localhost/api/foo/bar.jpeg', fakeReq)).toBe( + true + ); + expect(contextMatcher.match(pattern, 'http://localhost/api/foo/bar.gif', fakeReq)).toBe( + false + ); }); }); describe('Negation patterns', () => { it('should not match file extension', () => { const url = 'http://localhost/api/foo/bar.html'; - expect(contextMatcher.match(['**', '!**/*.html'], url, fakeReq)).toBe( - false - ); - expect(contextMatcher.match(['**', '!**/*.json'], url, fakeReq)).toBe( - true - ); + expect(contextMatcher.match(['**', '!**/*.html'], url, fakeReq)).toBe(false); + expect(contextMatcher.match(['**', '!**/*.json'], url, fakeReq)).toBe(true); }); }); }); @@ -321,11 +213,7 @@ describe('Context Matching', () => { beforeEach(() => { testContext = context => { return () => { - contextMatcher.match( - context, - 'http://localhost/api/foo/bar', - fakeReq - ); + contextMatcher.match(context, 'http://localhost/api/foo/bar', fakeReq); }; }; }); diff --git a/test/unit/handlers.spec.ts b/test/unit/handlers.spec.ts index 9890d2a6..0195ba8d 100644 --- a/test/unit/handlers.spec.ts +++ b/test/unit/handlers.spec.ts @@ -118,9 +118,7 @@ describe('default proxy error handler', () => { it('should end the response and return error message', () => { proxyError(mockError, mockReq, mockRes, proxyOptions); - expect(errorMessage).toBe( - 'Error occured while trying to proxy to: localhost:3000/api' - ); + expect(errorMessage).toBe('Error occured while trying to proxy to: localhost:3000/api'); }); it('should not set the http status code to: 500 if headers have already been sent', () => { @@ -132,8 +130,6 @@ describe('default proxy error handler', () => { it('should end the response and return error message', () => { mockRes.headersSent = true; proxyError(mockError, mockReq, mockRes, proxyOptions); - expect(errorMessage).toBe( - 'Error occured while trying to proxy to: localhost:3000/api' - ); + expect(errorMessage).toBe('Error occured while trying to proxy to: localhost:3000/api'); }); }); diff --git a/tsconfig.json b/tsconfig.json index 39528618..bba51431 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -5,8 +5,7 @@ "module": "commonjs", "moduleResolution": "node", "target": "es2015", - "declaration": true, - "esModuleInterop": true + "declaration": true }, "include": ["./src"] }