Skip to content

Commit 3e84b15

Browse files
authored
refactor: minor type improvements (#895)
1 parent f2a9fe4 commit 3e84b15

12 files changed

+62
-58
lines changed

src/handlers/response-interceptor.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -67,9 +67,9 @@ export function responseInterceptor<
6767
*/
6868
function decompress<TReq extends http.IncomingMessage = http.IncomingMessage>(
6969
proxyRes: TReq,
70-
contentEncoding: string
71-
): TReq {
72-
let _proxyRes = proxyRes;
70+
contentEncoding?: string
71+
): TReq | zlib.Gunzip | zlib.Inflate | zlib.BrotliDecompress {
72+
let _proxyRes: TReq | zlib.Gunzip | zlib.Inflate | zlib.BrotliDecompress = proxyRes;
7373
let decompress;
7474

7575
switch (contentEncoding) {

src/http-proxy-middleware.ts

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import type * as net from 'net';
12
import type * as http from 'http';
23
import type * as https from 'https';
34
import type { RequestHandler, Options, Filter } from './types';
@@ -38,7 +39,7 @@ export class HttpProxyMiddleware<TReq, TRes> {
3839
}
3940

4041
// https://github.com/Microsoft/TypeScript/wiki/'this'-in-TypeScript#red-flags-for-this
41-
public middleware: RequestHandler = async (req, res, next?) => {
42+
public middleware: RequestHandler = (async (req, res, next?) => {
4243
if (this.shouldProxy(this.proxyOptions.pathFilter, req)) {
4344
try {
4445
const activeProxyOptions = await this.prepareProxyRequest(req);
@@ -73,7 +74,7 @@ export class HttpProxyMiddleware<TReq, TRes> {
7374
// use initial request to access the server object to subscribe to http upgrade event
7475
this.catchUpgradeRequest(server);
7576
}
76-
};
77+
}) as RequestHandler;
7778

7879
private registerPlugins(proxy: httpProxy<TReq, TRes>, options: Options<TReq, TRes>) {
7980
const plugins = getPlugins<TReq, TRes>(options);
@@ -93,7 +94,7 @@ export class HttpProxyMiddleware<TReq, TRes> {
9394
}
9495
};
9596

96-
private handleUpgrade = async (req: http.IncomingMessage, socket, head) => {
97+
private handleUpgrade = async (req: http.IncomingMessage, socket: net.Socket, head: Buffer) => {
9798
if (this.shouldProxy(this.proxyOptions.pathFilter, req)) {
9899
const activeProxyOptions = await this.prepareProxyRequest(req);
99100
this.proxy.ws(req, socket, head, activeProxyOptions);
@@ -104,7 +105,10 @@ export class HttpProxyMiddleware<TReq, TRes> {
104105
/**
105106
* Determine whether request should be proxied.
106107
*/
107-
private shouldProxy = (pathFilter: Filter<TReq>, req: http.IncomingMessage): boolean => {
108+
private shouldProxy = (
109+
pathFilter: Filter<TReq> | undefined,
110+
req: http.IncomingMessage
111+
): boolean => {
108112
return matchPathFilter(pathFilter, req.url, req);
109113
};
110114

@@ -138,7 +142,7 @@ export class HttpProxyMiddleware<TReq, TRes> {
138142
};
139143

140144
// Modify option.target when router present.
141-
private applyRouter = async (req: http.IncomingMessage, options) => {
145+
private applyRouter = async (req: http.IncomingMessage, options: Options<TReq, TRes>) => {
142146
let newTarget;
143147

144148
if (options.router) {

src/legacy/options-adapter.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ export function legacyOptionsAdapter<TReq, TRes>(
2424
legacyContext: Filter<TReq> | LegacyOptions<TReq, TRes>,
2525
legacyOptions: LegacyOptions<TReq, TRes>
2626
): Options<TReq, TRes> {
27-
let options: LegacyOptions<TReq, TRes>;
27+
let options: LegacyOptions<TReq, TRes> = {};
2828
let logger: Logger;
2929

3030
// https://github.com/chimurai/http-proxy-middleware/pull/716
@@ -58,6 +58,8 @@ export function legacyOptionsAdapter<TReq, TRes>(
5858
} else if (legacyContext && !legacyOptions) {
5959
options = { ...(legacyContext as LegacyOptions<TReq, TRes>) };
6060
logger = getLegacyLogger(options);
61+
} else {
62+
logger = getLegacyLogger({}) as never;
6163
}
6264

6365
// map old event names to new event names

src/path-filter.ts

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import type * as http from 'http';
77

88
export function matchPathFilter<TReq = http.IncomingMessage>(
99
pathFilter: Filter<TReq> = '/',
10-
uri: string,
10+
uri: string | undefined,
1111
req: http.IncomingMessage
1212
): boolean {
1313
// single path
@@ -34,8 +34,8 @@ export function matchPathFilter<TReq = http.IncomingMessage>(
3434

3535
// custom matching
3636
if (typeof pathFilter === 'function') {
37-
const pathname = getUrlPathName(uri);
38-
return pathFilter(pathname, req as unknown as TReq);
37+
const pathname = getUrlPathName(uri) as string;
38+
return pathFilter(pathname, req as TReq);
3939
}
4040

4141
throw new Error(ERRORS.ERR_CONTEXT_MATCHER_GENERIC);
@@ -46,18 +46,18 @@ export function matchPathFilter<TReq = http.IncomingMessage>(
4646
* @param {String} uri 'http://example.org/api/b/c/d.html'
4747
* @return {Boolean}
4848
*/
49-
function matchSingleStringPath(pathFilter: string, uri: string) {
49+
function matchSingleStringPath(pathFilter: string, uri?: string) {
5050
const pathname = getUrlPathName(uri);
51-
return pathname.indexOf(pathFilter) === 0;
51+
return pathname?.indexOf(pathFilter) === 0;
5252
}
5353

54-
function matchSingleGlobPath(pattern: string | string[], uri: string) {
55-
const pathname = getUrlPathName(uri);
54+
function matchSingleGlobPath(pattern: string | string[], uri?: string) {
55+
const pathname = getUrlPathName(uri) as string;
5656
const matches = micromatch([pathname], pattern);
5757
return matches && matches.length > 0;
5858
}
5959

60-
function matchMultiGlobPath(patternList: string | string[], uri: string) {
60+
function matchMultiGlobPath(patternList: string | string[], uri?: string) {
6161
return matchSingleGlobPath(patternList, uri);
6262
}
6363

@@ -66,7 +66,7 @@ function matchMultiGlobPath(patternList: string | string[], uri: string) {
6666
* @param {String} uri 'http://example.org/api/b/c/d.html'
6767
* @return {Boolean}
6868
*/
69-
function matchMultiPath(pathFilterList: string[], uri: string) {
69+
function matchMultiPath(pathFilterList: string[], uri?: string) {
7070
let isMultiPath = false;
7171

7272
for (const context of pathFilterList) {
@@ -85,7 +85,7 @@ function matchMultiPath(pathFilterList: string[], uri: string) {
8585
* @param {String} uri from req.url
8686
* @return {String} RFC 3986 path
8787
*/
88-
function getUrlPathName(uri: string) {
88+
function getUrlPathName(uri?: string) {
8989
return uri && url.parse(uri).pathname;
9090
}
9191

src/path-rewriter.ts

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,14 +4,16 @@ import { Debug } from './debug';
44

55
const debug = Debug.extend('path-rewriter');
66

7+
type RewriteRule = { regex: RegExp; value: string };
8+
79
/**
810
* Create rewrite function, to cache parsed rewrite rules.
911
*
1012
* @param {Object} rewriteConfig
1113
* @return {Function} Function to rewrite paths; This function should accept `path` (request.url) as parameter
1214
*/
1315
export function createPathRewriter(rewriteConfig) {
14-
let rulesCache;
16+
let rulesCache: RewriteRule[];
1517

1618
if (!isValidRewriteConfig(rewriteConfig)) {
1719
return;
@@ -52,8 +54,8 @@ function isValidRewriteConfig(rewriteConfig) {
5254
}
5355
}
5456

55-
function parsePathRewriteRules(rewriteConfig) {
56-
const rules = [];
57+
function parsePathRewriteRules(rewriteConfig: Record<string, string>) {
58+
const rules: RewriteRule[] = [];
5759

5860
if (isPlainObj(rewriteConfig)) {
5961
for (const [key, value] of Object.entries(rewriteConfig)) {

src/plugins/default/error-response-plugin.ts

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,14 @@
11
import { getStatusCode } from '../../status-code';
22
import { Plugin } from '../../types';
3-
import type * as http from 'http';
43

54
export const errorResponsePlugin: Plugin = (proxyServer, options) => {
6-
proxyServer.on('error', (err, req, res: http.ServerResponse, target?) => {
5+
proxyServer.on('error', (err, req, res, target?) => {
76
// Re-throw error. Not recoverable since req & res are empty.
87
if (!req && !res) {
98
throw err; // "Error: Must provide a proper URL as target"
109
}
1110

12-
if (res.writeHead && !res.headersSent) {
11+
if ('writeHead' in res && !res.headersSent) {
1312
const statusCode = getStatusCode((err as unknown as any).code);
1413
res.writeHead(statusCode);
1514
}

src/types.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ export interface RequestHandler<
1717
TNext = NextFunction
1818
> {
1919
(req: TReq, res: TRes, next?: TNext): void | Promise<void>;
20-
upgrade?: (req: http.IncomingMessage, socket: net.Socket, head: any) => void;
20+
upgrade: (req: http.IncomingMessage, socket: net.Socket, head: Buffer) => void;
2121
}
2222

2323
export type Filter<TReq = http.IncomingMessage> =
@@ -67,7 +67,7 @@ export interface Options<TReq = http.IncomingMessage, TRes = http.ServerResponse
6767
*/
6868
pathRewrite?:
6969
| { [regexp: string]: string }
70-
| ((path: string, req: TReq) => string)
70+
| ((path: string, req: TReq) => string | undefined)
7171
| ((path: string, req: TReq) => Promise<string>);
7272
/**
7373
* Access the internal http-proxy server instance to customize behavior

test/e2e/express-error-middleware.spec.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ describe('express error middleware', () => {
1818
const app = createApp(proxyMiddleware, errorMiddleware);
1919
const response = await request(app).get('/get').expect(504);
2020

21-
expect(httpProxyError.message).toBe('Must provide a proper URL as target');
21+
expect(httpProxyError?.message).toBe('Must provide a proper URL as target');
2222
expect(response.text).toBe('Something broke!');
2323
});
2424
});

test/e2e/http-proxy-middleware.spec.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -256,7 +256,7 @@ describe('E2E http-proxy-middleware', () => {
256256
});
257257

258258
it('should send request header "host" to target server', async () => {
259-
let completedRequest: CompletedRequest;
259+
let completedRequest: CompletedRequest | undefined;
260260

261261
await mockTargetServer.forGet().thenCallback((req) => {
262262
completedRequest = req;
@@ -265,7 +265,7 @@ describe('E2E http-proxy-middleware', () => {
265265

266266
const response = await agent.get(`/api/some/endpoint/index.html`).expect(200);
267267
expect(response.text).toBe('OK');
268-
expect(completedRequest.headers.host).toBe('foobar.dev');
268+
expect(completedRequest?.headers.host).toBe('foobar.dev');
269269
});
270270
});
271271

@@ -374,15 +374,15 @@ describe('E2E http-proxy-middleware', () => {
374374
});
375375

376376
it('should add `x-added` as custom header to request"', async () => {
377-
let completedRequest: CompletedRequest;
377+
let completedRequest: CompletedRequest | undefined;
378378
await mockTargetServer.forGet().thenCallback((req) => {
379379
completedRequest = req;
380380
return { statusCode: 200 };
381381
});
382382

383383
await agent.get(`/api/foo/bar`).expect(200);
384384

385-
expect(completedRequest.headers['x-added']).toBe('added-from-hpm');
385+
expect(completedRequest?.headers['x-added']).toBe('added-from-hpm');
386386
});
387387
});
388388

test/e2e/plugins.spec.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,8 @@ describe('E2E Plugins', () => {
1616
});
1717

1818
it('should register a plugin and access the http-proxy object', async () => {
19-
let proxyReqUrl: string;
20-
let responseStatusCode: number;
19+
let proxyReqUrl: string | undefined;
20+
let responseStatusCode: number | undefined;
2121

2222
mockTargetServer.forGet('/users/1').thenReply(200, '{"userName":"John"}');
2323

0 commit comments

Comments
 (0)