http-proxy-middleware 2.0.6 → 3.0.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/README.md +280 -211
  2. package/dist/configuration.d.ts +2 -0
  3. package/dist/configuration.js +10 -0
  4. package/dist/debug.d.ts +5 -0
  5. package/dist/debug.js +8 -0
  6. package/dist/errors.d.ts +1 -1
  7. package/dist/errors.js +1 -1
  8. package/dist/get-plugins.d.ts +2 -0
  9. package/dist/get-plugins.js +15 -0
  10. package/dist/handlers/fix-request-body.d.ts +4 -1
  11. package/dist/handlers/index.js +5 -1
  12. package/dist/handlers/response-interceptor.d.ts +3 -2
  13. package/dist/handlers/response-interceptor.js +10 -1
  14. package/dist/http-proxy-middleware.d.ts +4 -11
  15. package/dist/http-proxy-middleware.js +39 -50
  16. package/dist/index.d.ts +13 -3
  17. package/dist/index.js +15 -3
  18. package/dist/legacy/create-proxy-middleware.d.ts +13 -0
  19. package/dist/legacy/create-proxy-middleware.js +17 -0
  20. package/dist/legacy/index.d.ts +1 -0
  21. package/dist/legacy/index.js +17 -0
  22. package/dist/legacy/options-adapter.d.ts +6 -0
  23. package/dist/legacy/options-adapter.js +92 -0
  24. package/dist/legacy/public.d.ts +2 -0
  25. package/dist/legacy/public.js +5 -0
  26. package/dist/legacy/types.d.ts +112 -0
  27. package/dist/legacy/types.js +2 -0
  28. package/dist/logger.d.ts +2 -14
  29. package/dist/logger.js +20 -129
  30. package/dist/path-filter.d.ts +4 -0
  31. package/dist/{context-matcher.js → path-filter.js} +24 -24
  32. package/dist/path-rewriter.js +6 -6
  33. package/dist/plugins/default/debug-proxy-errors-plugin.d.ts +6 -0
  34. package/dist/plugins/default/debug-proxy-errors-plugin.js +61 -0
  35. package/dist/plugins/default/error-response-plugin.d.ts +2 -0
  36. package/dist/plugins/default/error-response-plugin.js +19 -0
  37. package/dist/plugins/default/index.d.ts +4 -0
  38. package/dist/plugins/default/index.js +20 -0
  39. package/dist/plugins/default/logger-plugin.d.ts +2 -0
  40. package/dist/plugins/default/logger-plugin.js +44 -0
  41. package/dist/plugins/default/proxy-events.d.ts +22 -0
  42. package/dist/plugins/default/proxy-events.js +33 -0
  43. package/dist/router.js +7 -7
  44. package/dist/status-code.d.ts +1 -0
  45. package/dist/status-code.js +24 -0
  46. package/dist/types.d.ts +109 -38
  47. package/dist/utils/function.d.ts +1 -0
  48. package/dist/utils/function.js +8 -0
  49. package/package.json +37 -45
  50. package/dist/_handlers.d.ts +0 -4
  51. package/dist/_handlers.js +0 -84
  52. package/dist/config-factory.d.ts +0 -6
  53. package/dist/config-factory.js +0 -80
  54. package/dist/context-matcher.d.ts +0 -2
package/dist/router.js CHANGED
@@ -2,8 +2,8 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.getTarget = void 0;
4
4
  const isPlainObj = require("is-plain-obj");
5
- const logger_1 = require("./logger");
6
- const logger = (0, logger_1.getInstance)();
5
+ const debug_1 = require("./debug");
6
+ const debug = debug_1.Debug.extend('router');
7
7
  async function getTarget(req, config) {
8
8
  let newTarget;
9
9
  const router = config.router;
@@ -21,20 +21,20 @@ function getTargetFromProxyTable(req, table) {
21
21
  const host = req.headers.host;
22
22
  const path = req.url;
23
23
  const hostAndPath = host + path;
24
- for (const [key] of Object.entries(table)) {
24
+ for (const [key, value] of Object.entries(table)) {
25
25
  if (containsPath(key)) {
26
26
  if (hostAndPath.indexOf(key) > -1) {
27
27
  // match 'localhost:3000/api'
28
- result = table[key];
29
- logger.debug('[HPM] Router table match: "%s"', key);
28
+ result = value;
29
+ debug('match: "%s" -> "%s"', key, result);
30
30
  break;
31
31
  }
32
32
  }
33
33
  else {
34
34
  if (key === host) {
35
35
  // match 'localhost:3000'
36
- result = table[key];
37
- logger.debug('[HPM] Router table match: "%s"', host);
36
+ result = value;
37
+ debug('match: "%s" -> "%s"', host, result);
38
38
  break;
39
39
  }
40
40
  }
@@ -0,0 +1 @@
1
+ export declare function getStatusCode(errorCode: string): number;
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getStatusCode = void 0;
4
+ function getStatusCode(errorCode) {
5
+ let statusCode;
6
+ if (/HPE_INVALID/.test(errorCode)) {
7
+ statusCode = 502;
8
+ }
9
+ else {
10
+ switch (errorCode) {
11
+ case 'ECONNRESET':
12
+ case 'ENOTFOUND':
13
+ case 'ECONNREFUSED':
14
+ case 'ETIMEDOUT':
15
+ statusCode = 504;
16
+ break;
17
+ default:
18
+ statusCode = 500;
19
+ break;
20
+ }
21
+ }
22
+ return statusCode;
23
+ }
24
+ exports.getStatusCode = getStatusCode;
package/dist/types.d.ts CHANGED
@@ -3,52 +3,123 @@
3
3
  * https://github.com/DefinitelyTyped/DefinitelyTyped/blob/6f529c6c67a447190f86bfbf894d1061e41e07b7/types/http-proxy-middleware/index.d.ts
4
4
  */
5
5
  /// <reference types="node" />
6
- import type * as express from 'express';
6
+ /// <reference types="node" />
7
+ /// <reference types="node" />
7
8
  import type * as http from 'http';
8
9
  import type * as httpProxy from 'http-proxy';
9
10
  import type * as net from 'net';
10
- import type * as url from 'url';
11
- export interface Request extends express.Request {
11
+ export declare type NextFunction<T = (err?: any) => void> = T;
12
+ export interface RequestHandler<TReq = http.IncomingMessage, TRes = http.ServerResponse, TNext = NextFunction> {
13
+ (req: TReq, res: TRes, next?: TNext): void | Promise<void>;
14
+ upgrade?: (req: http.IncomingMessage, socket: net.Socket, head: any) => void;
12
15
  }
13
- export interface Response extends express.Response {
16
+ export declare type Filter<TReq = http.IncomingMessage> = string | string[] | ((pathname: string, req: TReq) => boolean);
17
+ export interface Plugin<TReq = http.IncomingMessage, TRes = http.ServerResponse> {
18
+ (proxyServer: httpProxy<TReq, TRes>, options: Options<TReq, TRes>): void;
14
19
  }
15
- export interface RequestHandler extends express.RequestHandler {
16
- upgrade?: (req: Request, socket: net.Socket, head: any) => void;
20
+ export interface OnProxyEvent<TReq = http.IncomingMessage, TRes = http.ServerResponse> {
21
+ error?: httpProxy.ErrorCallback<Error, TReq, TRes>;
22
+ proxyReq?: httpProxy.ProxyReqCallback<http.ClientRequest, TReq, TRes>;
23
+ proxyReqWs?: httpProxy.ProxyReqWsCallback<http.ClientRequest, TReq>;
24
+ proxyRes?: httpProxy.ProxyResCallback<TReq, TRes>;
25
+ open?: httpProxy.OpenCallback;
26
+ close?: httpProxy.CloseCallback<TReq>;
27
+ start?: httpProxy.StartCallback<TReq, TRes>;
28
+ end?: httpProxy.EndCallback<TReq, TRes>;
29
+ econnreset?: httpProxy.EconnresetCallback<Error, TReq, TRes>;
17
30
  }
18
- export declare type Filter = string | string[] | ((pathname: string, req: Request) => boolean);
19
- export interface Options extends httpProxy.ServerOptions {
31
+ export declare type Logger = Pick<Console, 'info' | 'warn' | 'error'>;
32
+ export interface Options<TReq = http.IncomingMessage, TRes = http.ServerResponse> extends httpProxy.ServerOptions {
33
+ /**
34
+ * Narrow down requests to proxy or not.
35
+ * Filter on {@link http.IncomingMessage.url `pathname`} which is relative to the proxy's "mounting" point in the server.
36
+ * Or use the {@link http.IncomingMessage `req`} object for more complex filtering.
37
+ * @link https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/pathFilter.md
38
+ * @since v3.0.0
39
+ */
40
+ pathFilter?: Filter<TReq>;
41
+ /**
42
+ * Modify request paths before requests are send to the target.
43
+ * @example
44
+ * ```js
45
+ * createProxyMiddleware({
46
+ * pathRewrite: {
47
+ * '^/api/old-path': '/api/new-path', // rewrite path
48
+ * }
49
+ * });
50
+ * ```
51
+ * @link https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/pathRewrite.md
52
+ */
20
53
  pathRewrite?: {
21
54
  [regexp: string]: string;
22
- } | ((path: string, req: Request) => string) | ((path: string, req: Request) => Promise<string>);
55
+ } | ((path: string, req: TReq) => string) | ((path: string, req: TReq) => Promise<string>);
56
+ /**
57
+ * Access the internal http-proxy server instance to customize behavior
58
+ *
59
+ * @example
60
+ * ```js
61
+ * createProxyMiddleware({
62
+ * plugins: [(proxyServer, options) => {
63
+ * proxyServer.on('error', (error, req, res) => {
64
+ * console.error(error);
65
+ * });
66
+ * }]
67
+ * });
68
+ * ```
69
+ * @link https://github.com/chimurai/http-proxy-middleware#plugins-array
70
+ * @since v3.0.0
71
+ */
72
+ plugins?: Plugin<TReq, TRes>[];
73
+ /**
74
+ * Eject pre-configured plugins.
75
+ * NOTE: register your own error handlers to prevent server from crashing.
76
+ *
77
+ * @link https://github.com/chimurai/http-proxy-middleware#ejectplugins-boolean-default-false
78
+ * @since v3.0.0
79
+ */
80
+ ejectPlugins?: boolean;
81
+ /**
82
+ * Listen to http-proxy events
83
+ * @see {@link OnProxyEvent} for available events
84
+ * @example
85
+ * ```js
86
+ * createProxyMiddleware({
87
+ * on: {
88
+ * error: (error, req, res, target) => {
89
+ * console.error(error);
90
+ * }
91
+ * }
92
+ * });
93
+ * ```
94
+ * @link https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/proxy-events.md
95
+ * @since v3.0.0
96
+ */
97
+ on?: OnProxyEvent<TReq, TRes>;
98
+ /**
99
+ * Dynamically set the {@link Options.target `options.target`}.
100
+ * @example
101
+ * ```js
102
+ * createProxyMiddleware({
103
+ * router: async (req) => {
104
+ * return 'http://127:0.0.1:3000';
105
+ * }
106
+ * });
107
+ * ```
108
+ * @link https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/router.md
109
+ */
23
110
  router?: {
24
111
  [hostOrPath: string]: httpProxy.ServerOptions['target'];
25
- } | ((req: Request) => httpProxy.ServerOptions['target']) | ((req: Request) => Promise<httpProxy.ServerOptions['target']>);
26
- logLevel?: 'debug' | 'info' | 'warn' | 'error' | 'silent';
27
- logProvider?: LogProviderCallback;
28
- onError?: OnErrorCallback;
29
- onProxyRes?: OnProxyResCallback;
30
- onProxyReq?: OnProxyReqCallback;
31
- onProxyReqWs?: OnProxyReqWsCallback;
32
- onOpen?: OnOpenCallback;
33
- onClose?: OnCloseCallback;
34
- }
35
- interface LogProvider {
36
- log: Logger;
37
- debug?: Logger;
38
- info?: Logger;
39
- warn?: Logger;
40
- error?: Logger;
112
+ } | ((req: TReq) => httpProxy.ServerOptions['target']) | ((req: TReq) => Promise<httpProxy.ServerOptions['target']>);
113
+ /**
114
+ * Log information from http-proxy-middleware
115
+ * @example
116
+ * ```js
117
+ * createProxyMiddleware({
118
+ * logger: console
119
+ * });
120
+ * ```
121
+ * @link https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/logger.md
122
+ * @since v3.0.0
123
+ */
124
+ logger?: Logger | any;
41
125
  }
42
- declare type Logger = (...args: any[]) => void;
43
- export declare type LogProviderCallback = (provider: LogProvider) => LogProvider;
44
- /**
45
- * Use types based on the events listeners from http-proxy
46
- * https://github.com/DefinitelyTyped/DefinitelyTyped/blob/51504fd999031b7f025220fab279f1b2155cbaff/types/http-proxy/index.d.ts
47
- */
48
- export declare type OnErrorCallback = (err: Error, req: Request, res: Response, target?: string | Partial<url.Url>) => void;
49
- export declare type OnProxyResCallback = (proxyRes: http.IncomingMessage, req: Request, res: Response) => void;
50
- export declare type OnProxyReqCallback = (proxyReq: http.ClientRequest, req: Request, res: Response, options: httpProxy.ServerOptions) => void;
51
- export declare type OnProxyReqWsCallback = (proxyReq: http.ClientRequest, req: Request, socket: net.Socket, options: httpProxy.ServerOptions, head: any) => void;
52
- export declare type OnCloseCallback = (proxyRes: Response, proxySocket: net.Socket, proxyHead: any) => void;
53
- export declare type OnOpenCallback = (proxySocket: net.Socket) => void;
54
- export {};
@@ -0,0 +1 @@
1
+ export declare function getFunctionName(fn: Function): string;
@@ -0,0 +1,8 @@
1
+ "use strict";
2
+ /* eslint-disable @typescript-eslint/ban-types */
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.getFunctionName = void 0;
5
+ function getFunctionName(fn) {
6
+ return fn.name || '[anonymous Function]';
7
+ }
8
+ exports.getFunctionName = getFunctionName;
package/package.json CHANGED
@@ -1,28 +1,25 @@
1
1
  {
2
2
  "name": "http-proxy-middleware",
3
- "version": "2.0.6",
4
- "description": "The one-liner node.js proxy middleware for connect, express and browser-sync",
3
+ "version": "3.0.0-beta.1",
4
+ "description": "The one-liner node.js proxy middleware for connect, express, next.js and more",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
7
7
  "files": [
8
8
  "dist"
9
9
  ],
10
10
  "scripts": {
11
- "clean": "rm -rf dist && rm -rf coverage",
11
+ "clean": "rm -rf dist coverage tsconfig.tsbuildinfo .eslintcache",
12
12
  "lint": "yarn prettier && yarn eslint",
13
13
  "lint:fix": "yarn prettier:fix && yarn eslint:fix",
14
- "eslint": "eslint '{src,test}/**/*.ts'",
14
+ "eslint": "eslint '{src,test}/**/*.ts' --cache",
15
15
  "eslint:fix": "yarn eslint --fix",
16
16
  "prettier": "prettier --list-different \"**/*.{js,ts,md,yml,json,html}\"",
17
17
  "prettier:fix": "prettier --write \"**/*.{js,ts,md,yml,json,html}\"",
18
- "prebuild": "yarn clean",
19
- "build": "tsc",
20
- "pretest": "yarn build",
18
+ "build": "tsc --build",
21
19
  "test": "jest",
22
- "precoverage": "yarn build",
23
- "coverage": "jest --coverage --coverageReporters=lcov",
20
+ "coverage": "jest --coverage",
24
21
  "prepare": "husky install",
25
- "prepack": "yarn build && rm dist/tsconfig.tsbuildinfo",
22
+ "prepack": "yarn clean && yarn test && yarn build",
26
23
  "spellcheck": "npx --yes cspell --show-context --show-suggestions '**/*.*'"
27
24
  },
28
25
  "repository": {
@@ -39,6 +36,7 @@
39
36
  "express",
40
37
  "fastify",
41
38
  "polka",
39
+ "next.js",
42
40
  "browser-sync",
43
41
  "gulp",
44
42
  "grunt-contrib-connect",
@@ -53,50 +51,44 @@
53
51
  },
54
52
  "homepage": "https://github.com/chimurai/http-proxy-middleware#readme",
55
53
  "devDependencies": {
56
- "@commitlint/cli": "16.2.1",
57
- "@commitlint/config-conventional": "16.2.1",
58
- "@types/express": "4.17.13",
54
+ "@commitlint/cli": "17.4.4",
55
+ "@commitlint/config-conventional": "17.4.4",
56
+ "@types/debug": "4.1.7",
57
+ "@types/express": "4.17.17",
59
58
  "@types/is-glob": "4.0.2",
60
- "@types/jest": "27.4.0",
59
+ "@types/jest": "29.4.0",
61
60
  "@types/micromatch": "4.0.2",
62
- "@types/node": "17.0.18",
63
- "@types/supertest": "2.0.11",
64
- "@types/ws": "8.2.2",
65
- "@typescript-eslint/eslint-plugin": "5.12.0",
66
- "@typescript-eslint/parser": "5.12.0",
67
- "body-parser": "1.19.2",
68
- "browser-sync": "2.27.7",
61
+ "@types/node": "18.14.5",
62
+ "@types/supertest": "2.0.12",
63
+ "@types/ws": "8.5.4",
64
+ "@typescript-eslint/eslint-plugin": "5.54.0",
65
+ "@typescript-eslint/parser": "5.54.0",
66
+ "body-parser": "1.20.2",
67
+ "browser-sync": "2.28.1",
69
68
  "connect": "3.7.0",
70
- "eslint": "8.9.0",
71
- "eslint-config-prettier": "8.3.0",
72
- "eslint-plugin-prettier": "4.0.0",
73
- "express": "4.17.3",
69
+ "eslint": "8.35.0",
70
+ "eslint-config-prettier": "8.6.0",
71
+ "eslint-plugin-prettier": "4.2.1",
72
+ "express": "4.18.2",
74
73
  "get-port": "5.1.1",
75
- "husky": "7.0.4",
76
- "jest": "27.5.1",
77
- "lint-staged": "12.3.4",
78
- "mockttp": "2.6.0",
79
- "open": "8.4.0",
80
- "prettier": "2.5.1",
81
- "supertest": "6.2.2",
82
- "ts-jest": "27.1.3",
83
- "typescript": "4.5.5",
84
- "ws": "8.5.0"
74
+ "husky": "8.0.3",
75
+ "jest": "29.4.3",
76
+ "lint-staged": "13.1.2",
77
+ "mockttp": "3.7.0",
78
+ "open": "8.4.2",
79
+ "prettier": "2.8.4",
80
+ "supertest": "6.3.3",
81
+ "ts-jest": "29.0.5",
82
+ "typescript": "4.9.5",
83
+ "ws": "8.12.1"
85
84
  },
86
85
  "dependencies": {
87
- "@types/http-proxy": "^1.17.8",
86
+ "@types/http-proxy": "^1.17.10",
87
+ "debug": "^4.3.4",
88
88
  "http-proxy": "^1.18.1",
89
89
  "is-glob": "^4.0.1",
90
90
  "is-plain-obj": "^3.0.0",
91
- "micromatch": "^4.0.2"
92
- },
93
- "peerDependencies": {
94
- "@types/express": "^4.17.13"
95
- },
96
- "peerDependenciesMeta": {
97
- "@types/express": {
98
- "optional": true
99
- }
91
+ "micromatch": "^4.0.5"
100
92
  },
101
93
  "engines": {
102
94
  "node": ">=12.0.0"
@@ -1,4 +0,0 @@
1
- import type { Options } from './types';
2
- import type * as httpProxy from 'http-proxy';
3
- export declare function init(proxy: httpProxy, option: Options): void;
4
- export declare function getHandlers(options: Options): any;
package/dist/_handlers.js DELETED
@@ -1,84 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getHandlers = exports.init = void 0;
4
- const logger_1 = require("./logger");
5
- const logger = (0, logger_1.getInstance)();
6
- function init(proxy, option) {
7
- const handlers = getHandlers(option);
8
- for (const eventName of Object.keys(handlers)) {
9
- proxy.on(eventName, handlers[eventName]);
10
- }
11
- // https://github.com/webpack/webpack-dev-server/issues/1642
12
- proxy.on('econnreset', (error, req, res, target) => {
13
- logger.error(`[HPM] ECONNRESET: %O`, error);
14
- });
15
- // https://github.com/webpack/webpack-dev-server/issues/1642#issuecomment-1104325120
16
- proxy.on('proxyReqWs', (proxyReq, req, socket, options, head) => {
17
- socket.on('error', (error) => {
18
- logger.error(`[HPM] WebSocket error: %O`, error);
19
- });
20
- });
21
- logger.debug('[HPM] Subscribed to http-proxy events:', Object.keys(handlers));
22
- }
23
- exports.init = init;
24
- function getHandlers(options) {
25
- // https://github.com/nodejitsu/node-http-proxy#listening-for-proxy-events
26
- const proxyEventsMap = {
27
- error: 'onError',
28
- proxyReq: 'onProxyReq',
29
- proxyReqWs: 'onProxyReqWs',
30
- proxyRes: 'onProxyRes',
31
- open: 'onOpen',
32
- close: 'onClose',
33
- };
34
- const handlers = {};
35
- for (const [eventName, onEventName] of Object.entries(proxyEventsMap)) {
36
- // all handlers for the http-proxy events are prefixed with 'on'.
37
- // loop through options and try to find these handlers
38
- // and add them to the handlers object for subscription in init().
39
- const fnHandler = options ? options[onEventName] : null;
40
- if (typeof fnHandler === 'function') {
41
- handlers[eventName] = fnHandler;
42
- }
43
- }
44
- // add default error handler in absence of error handler
45
- if (typeof handlers.error !== 'function') {
46
- handlers.error = defaultErrorHandler;
47
- }
48
- // add default close handler in absence of close handler
49
- if (typeof handlers.close !== 'function') {
50
- handlers.close = logClose;
51
- }
52
- return handlers;
53
- }
54
- exports.getHandlers = getHandlers;
55
- function defaultErrorHandler(err, req, res) {
56
- // Re-throw error. Not recoverable since req & res are empty.
57
- if (!req && !res) {
58
- throw err; // "Error: Must provide a proper URL as target"
59
- }
60
- const host = req.headers && req.headers.host;
61
- const code = err.code;
62
- if (res.writeHead && !res.headersSent) {
63
- if (/HPE_INVALID/.test(code)) {
64
- res.writeHead(502);
65
- }
66
- else {
67
- switch (code) {
68
- case 'ECONNRESET':
69
- case 'ENOTFOUND':
70
- case 'ECONNREFUSED':
71
- case 'ETIMEDOUT':
72
- res.writeHead(504);
73
- break;
74
- default:
75
- res.writeHead(500);
76
- }
77
- }
78
- }
79
- res.end(`Error occurred while trying to proxy: ${host}${req.url}`);
80
- }
81
- function logClose(req, socket, head) {
82
- // view disconnected websocket connections
83
- logger.info('[HPM] Client disconnected');
84
- }
@@ -1,6 +0,0 @@
1
- import { Filter, Options } from './types';
2
- export declare type Config = {
3
- context: Filter;
4
- options: Options;
5
- };
6
- export declare function createConfig(context: any, opts?: Options): Config;
@@ -1,80 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.createConfig = void 0;
4
- const isPlainObj = require("is-plain-obj");
5
- const url = require("url");
6
- const errors_1 = require("./errors");
7
- const logger_1 = require("./logger");
8
- const logger = (0, logger_1.getInstance)();
9
- function createConfig(context, opts) {
10
- // structure of config object to be returned
11
- const config = {
12
- context: undefined,
13
- options: {},
14
- };
15
- // app.use('/api', proxy({target:'http://localhost:9000'}));
16
- if (isContextless(context, opts)) {
17
- config.context = '/';
18
- config.options = Object.assign(config.options, context);
19
- // app.use('/api', proxy('http://localhost:9000'));
20
- // app.use(proxy('http://localhost:9000/api'));
21
- }
22
- else if (isStringShortHand(context)) {
23
- const oUrl = url.parse(context);
24
- const target = [oUrl.protocol, '//', oUrl.host].join('');
25
- config.context = oUrl.pathname || '/';
26
- config.options = Object.assign(config.options, { target }, opts);
27
- if (oUrl.protocol === 'ws:' || oUrl.protocol === 'wss:') {
28
- config.options.ws = true;
29
- }
30
- // app.use('/api', proxy({target:'http://localhost:9000'}));
31
- }
32
- else {
33
- config.context = context;
34
- config.options = Object.assign(config.options, opts);
35
- }
36
- configureLogger(config.options);
37
- if (!config.options.target && !config.options.router) {
38
- throw new Error(errors_1.ERRORS.ERR_CONFIG_FACTORY_TARGET_MISSING);
39
- }
40
- return config;
41
- }
42
- exports.createConfig = createConfig;
43
- /**
44
- * Checks if a String only target/config is provided.
45
- * This can be just the host or with the optional path.
46
- *
47
- * @example
48
- * app.use('/api', proxy('http://localhost:9000'));
49
- * app.use(proxy('http://localhost:9000/api'));
50
- *
51
- * @param {String} context [description]
52
- * @return {Boolean} [description]
53
- */
54
- function isStringShortHand(context) {
55
- if (typeof context === 'string') {
56
- return !!url.parse(context).host;
57
- }
58
- }
59
- /**
60
- * Checks if a Object only config is provided, without a context.
61
- * In this case the all paths will be proxied.
62
- *
63
- * @example
64
- * app.use('/api', proxy({target:'http://localhost:9000'}));
65
- *
66
- * @param {Object} context [description]
67
- * @param {*} opts [description]
68
- * @return {Boolean} [description]
69
- */
70
- function isContextless(context, opts) {
71
- return isPlainObj(context) && (opts == null || Object.keys(opts).length === 0);
72
- }
73
- function configureLogger(options) {
74
- if (options.logLevel) {
75
- logger.setLevel(options.logLevel);
76
- }
77
- if (options.logProvider) {
78
- logger.setProvider(options.logProvider);
79
- }
80
- }
@@ -1,2 +0,0 @@
1
- import type { Filter, Request } from './types';
2
- export declare function match(context: Filter, uri: string, req: Request): boolean;