Skip to content

Commit d6b9fee

Browse files
fix: normalize middle wildcards, call path-to-regexp early
1 parent d944fa5 commit d6b9fee

File tree

2 files changed

+17
-2
lines changed

2 files changed

+17
-2
lines changed

packages/core/router/legacy-route-converter.ts

+14-2
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ export class LegacyRouteConverter {
1414
* @returns The converted route, or the original route if it cannot be converted.
1515
*/
1616
static tryConvert(route: string): string {
17-
// Normalize path to eliminate additional conditions.
17+
// Normalize path to eliminate additional if statements.
1818
const routeWithLeadingSlash = route.startsWith('/') ? route : `/${route}`;
1919
const normalizedRoute = route.endsWith('/')
2020
? routeWithLeadingSlash
@@ -27,17 +27,29 @@ export class LegacyRouteConverter {
2727
}
2828
return route.replace('(.*)', '{*path}');
2929
}
30+
3031
if (normalizedRoute.endsWith('/*/')) {
3132
// Skip printing warning for the "all" wildcard.
3233
if (normalizedRoute !== '/*/') {
3334
this.printWarning(route);
3435
}
3536
return route.replace('*', '{*path}');
3637
}
38+
3739
if (normalizedRoute.endsWith('/+/')) {
3840
this.printWarning(route);
3941
return route.replace('/+', '/*path');
4042
}
43+
44+
// When route includes any wildcard segments in the middle.
45+
if (normalizedRoute.includes('/*/')) {
46+
this.printWarning(route);
47+
// Replace each /*/ segment with a named parameter using different name for each segment.
48+
return route.replaceAll('/*/', (match, offset) => {
49+
return `/*path${offset}/`;
50+
});
51+
}
52+
4153
return route;
4254
}
4355

@@ -47,7 +59,7 @@ export class LegacyRouteConverter {
4759

4860
static printWarning(route: string): void {
4961
this.logger.warn(
50-
UNSUPPORTED_PATH_MESSAGE`${route}` + ' Attempting to convert...',
62+
UNSUPPORTED_PATH_MESSAGE`${route}` + ' Attempting to auto-convert...',
5163
);
5264
}
5365
}

packages/platform-express/adapters/express-adapter.ts

+3
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ import * as express from 'express';
3434
import type { Server } from 'http';
3535
import * as http from 'http';
3636
import * as https from 'https';
37+
import { pathToRegexp } from 'path-to-regexp';
3738
import { Duplex, pipeline } from 'stream';
3839
import { NestExpressBodyParserOptions } from '../interfaces/nest-express-body-parser-options.interface';
3940
import { NestExpressBodyParserType } from '../interfaces/nest-express-body-parser.interface';
@@ -159,6 +160,8 @@ export class ExpressAdapter extends AbstractHttpAdapter<
159160
public normalizePath(path: string): string {
160161
try {
161162
const convertedPath = LegacyRouteConverter.tryConvert(path);
163+
// Call "pathToRegexp" to trigger a TypeError if the path is invalid
164+
pathToRegexp(convertedPath);
162165
return convertedPath;
163166
} catch (e) {
164167
if (e instanceof TypeError) {

0 commit comments

Comments
 (0)