1
1
import { NextApiResponse , NextApiRequest } from "next" ;
2
2
import httpProxy , { ServerOptions } from "http-proxy" ;
3
3
export interface NextHttpProxyMiddlewareOptions extends ServerOptions {
4
- pathRewrite ?: { [ key : string ] : string } ;
4
+ pathRewrite ?: { [ key : string ] : string }
5
+ | { patternStr : string , replaceStr : string } [ ] ;
5
6
}
6
7
7
8
/**
@@ -10,20 +11,35 @@ export interface NextHttpProxyMiddlewareOptions extends ServerOptions {
10
11
const proxy : httpProxy = httpProxy . createProxy ( ) ;
11
12
12
13
/**
13
- * If a key pattern is found in `pathRewrite` that matches the url value,
14
- * replace matched string of url with the `pathRewrite` value.
15
- * @param req
14
+ * If pattern information matching the input url information is found in the `pathRewrite` array,
15
+ * the url value is partially replaced with the `pathRewrite.replaceStr ` value.
16
+ * @param url
16
17
* @param pathRewrite
17
18
*/
18
19
export const rewritePath = (
19
20
url : string ,
20
- pathRewrite : { [ key : string ] : string }
21
+ pathRewrite : NextHttpProxyMiddlewareOptions [ 'pathRewrite' ]
21
22
) => {
22
- for ( let patternStr in pathRewrite ) {
23
- const pattern = RegExp ( patternStr ) ;
24
- const path = pathRewrite [ patternStr ] ;
25
- if ( pattern . test ( url as string ) ) {
26
- return url . replace ( pattern , path ) ;
23
+ if ( Array . isArray ( pathRewrite ) ) {
24
+ for ( let item of pathRewrite ) {
25
+ const {
26
+ patternStr,
27
+ replaceStr
28
+ } = item ;
29
+ const pattern = RegExp ( patternStr ) ;
30
+ if ( pattern . test ( url as string ) ) {
31
+ return url . replace ( pattern , replaceStr ) ;
32
+ }
33
+ }
34
+ } else {
35
+ console . warn ( '[next-http-proxy-middleware] Use array instead of object for \`pathRewrite\` value '
36
+ + '(related issue: https://github.com/stegano/next-http-proxy-middleware/issues/39)' ) ;
37
+ for ( let patternStr in pathRewrite ) {
38
+ const pattern = RegExp ( patternStr ) ;
39
+ const path = pathRewrite [ patternStr ] ;
40
+ if ( pattern . test ( url as string ) ) {
41
+ return url . replace ( pattern , path ) ;
42
+ }
27
43
}
28
44
}
29
45
return url ;
0 commit comments