Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(core): resolve :param retrieval in prefix in middleware #13886

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
109 changes: 109 additions & 0 deletions integration/hello-world/e2e/middleware-fastify.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -398,4 +398,113 @@ describe('Middleware (FastifyAdapter)', () => {
await app.close();
});
});

describe('should work properly when globalPrefix is set', () => {
class Middleware implements NestMiddleware {
use(request: any, reply: any, next: () => void) {
if (request.middlewareExecutionCount === undefined) {
request.middlewareExecutionCount = 1;
} else {
request.middlewareExecutionCount++;
}
next();
}
}

@Controller()
class AbcController {
@Get('/a')
async a(@Req() request: any) {
return this.validateExecutionCount({
request,
expected: 1,
});
}

@Get('/')
async root(@Req() request: any) {
return this.validateExecutionCount({
request,
expected: 1,
});
}

private validateExecutionCount({
request,
expected,
}: {
request: any;
expected: number;
}) {
let actual: number | undefined;
actual = request.raw.middlewareExecutionCount;
actual ??= 0;

return {
success: actual === expected,
actual,
expected,
};
}
}

@Module({
controllers: [AbcController],
})
class TestModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer.apply(Middleware).forRoutes(AbcController);
}
}

beforeEach(async () => {
app = (
await Test.createTestingModule({
imports: [TestModule],
}).compile()
).createNestApplication<NestFastifyApplication>(new FastifyAdapter());

app.setGlobalPrefix('api', { exclude: ['/'] });

await app.init();
});

it(`GET forRoutes(/api/a)`, () => {
return app
.inject({
method: 'GET',
url: '/api/a',
})
.then(({ payload }) =>
expect(payload).to.be.eql(
JSON.stringify({
success: true,
actual: 1,
expected: 1,
}),
),
);
});

it(`GET forRoutes(/)`, () => {
return app
.inject({
method: 'GET',
url: '/',
})
.then(({ payload }) =>
expect(payload).to.be.eql(
JSON.stringify({
success: true,
actual: 1,
expected: 1,
}),
),
);
});

afterEach(async () => {
await app.close();
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,17 @@ describe('Global prefix', () => {
.expect(200, { '0': 'params', tenantId: 'test' });
});

it(`should get the params in the global prefix with exclude option`, async () => {
app.setGlobalPrefix('/api/:tenantId', { exclude: ['/'] });

server = app.getHttpServer();
await app.init();

await request(server)
.get('/api/test/params')
.expect(200, { '0': 'params', tenantId: 'test' });
});

it(`should execute middleware only once`, async () => {
app.setGlobalPrefix('/api', { exclude: ['/'] });

Expand Down
6 changes: 1 addition & 5 deletions packages/core/middleware/middleware-module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -329,11 +329,7 @@ export class MiddlewareModule<
}
return next();
};
const pathsToApplyMiddleware = [];
paths.some(path => path.match(/^\/?$/))
? pathsToApplyMiddleware.push('/')
: pathsToApplyMiddleware.push(...paths);
pathsToApplyMiddleware.forEach(path => router(path, middlewareFunction));
paths.forEach(path => router(path, middlewareFunction));
}

private getContextId(request: unknown, isTreeDurable: boolean): ContextId {
Expand Down
62 changes: 40 additions & 22 deletions packages/core/middleware/route-info-path-extractor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,32 +30,36 @@ export class RouteInfoPathExtractor {
}

public extractPathsFrom({ path, method, version }: RouteInfo): string[] {
if (!this.isAWildcard(path)) {
return this.extractNonWildcardPathsFrom({ path, method, version });
}

if (!this.hasParamInPrefixPath()) {
return [addLeadingSlash(path)];
}

// The following logic is for cases where `prefixPath` contains `:param`.
// To resolve https://github.com/nestjs/nest/issues/9776
const versionPaths = this.extractVersionPathFrom(version);
const prefixes = this.combinePaths(this.prefixPath, versionPaths);
const entries = [
...prefixes.filter(Boolean).map(prefix => prefix + '$'),
...this.combinePaths(prefixes, addLeadingSlash(path)),
];

if (this.isAWildcard(path)) {
const entries =
versionPaths.length > 0
? versionPaths
.map(versionPath => [
this.prefixPath + versionPath + '$',
this.prefixPath + versionPath + addLeadingSlash(path),
])
.flat()
: this.prefixPath
? [this.prefixPath + '$', this.prefixPath + addLeadingSlash(path)]
: [addLeadingSlash(path)];

return Array.isArray(this.excludedGlobalPrefixRoutes)
? [
...entries,
...this.excludedGlobalPrefixRoutes.map(
route => versionPaths + addLeadingSlash(route.path),
),
]
: entries;
if (
Array.isArray(this.excludedGlobalPrefixRoutes) &&
this.excludedGlobalPrefixRoutes.length
) {
const excludedGlobalPrefixPaths = this.excludedGlobalPrefixRoutes
.map(route =>
this.combinePaths(versionPaths, addLeadingSlash(route.path + '$')),
)
.flat();
entries.push(...excludedGlobalPrefixPaths);
}

return this.extractNonWildcardPathsFrom({ path, method, version });
return entries;
}

public extractPathFrom(route: RouteInfo): string[] {
Expand All @@ -66,6 +70,10 @@ export class RouteInfoPathExtractor {
return this.extractNonWildcardPathsFrom(route);
}

private hasParamInPrefixPath(): boolean {
return this.prefixPath.includes(':');
}

private isAWildcard(path: string): boolean {
return ['*', '/*', '/*/', '(.*)', '/(.*)'].includes(path);
}
Expand Down Expand Up @@ -113,4 +121,14 @@ export class RouteInfoPathExtractor {
}
return [addLeadingSlash(versionPrefix + versionValue.toString())];
}

public combinePaths(a: string | string[], b: string | string[]): string[] {
const formatter = (path: string | string[]) => {
return Array.isArray(path) ? (path.length > 0 ? path : ['']) : [path];
};

const aArr = formatter(a);
const bArr = formatter(b);
return aArr.map(a => bArr.map(b => a + b)).flat();
}
}
69 changes: 64 additions & 5 deletions packages/core/test/middleware/route-info-path-extractor.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ describe('RouteInfoPathExtractor', () => {
method: RequestMethod.ALL,
version: '1',
}),
).to.eql(['/v1$', '/v1/*']);
).to.eql(['/*']);
});

it(`should return correct paths when set global prefix`, () => {
Expand All @@ -42,15 +42,34 @@ describe('RouteInfoPathExtractor', () => {
path: '*',
method: RequestMethod.ALL,
}),
).to.eql(['/api$', '/api/*']);
).to.eql(['/*']);

expect(
routeInfoPathExtractor.extractPathsFrom({
path: '*',
method: RequestMethod.ALL,
version: '1',
}),
).to.eql(['/*']);
});

it(`should return correct paths when set global prefix (has :param)`, () => {
Reflect.set(routeInfoPathExtractor, 'prefixPath', '/:param');

expect(
routeInfoPathExtractor.extractPathsFrom({
path: '*',
method: RequestMethod.ALL,
}),
).to.eql(['/:param$', '/:param/*']);

expect(
routeInfoPathExtractor.extractPathsFrom({
path: '*',
method: RequestMethod.ALL,
version: '1',
}),
).to.eql(['/api/v1$', '/api/v1/*']);
).to.eql(['/:param/v1$', '/:param/v1/*']);
});

it(`should return correct paths when set global prefix and global prefix options`, () => {
Expand All @@ -66,15 +85,15 @@ describe('RouteInfoPathExtractor', () => {
path: '*',
method: RequestMethod.ALL,
}),
).to.eql(['/api$', '/api/*', '/foo']);
).to.eql(['/*']);

expect(
routeInfoPathExtractor.extractPathsFrom({
path: '*',
method: RequestMethod.ALL,
version: '1',
}),
).to.eql(['/api/v1$', '/api/v1/*', '/v1/foo']);
).to.eql(['/*']);

expect(
routeInfoPathExtractor.extractPathsFrom({
Expand All @@ -92,6 +111,46 @@ describe('RouteInfoPathExtractor', () => {
}),
).to.eql(['/api/v1/bar']);
});

it(`should return correct paths when set global prefix (has :param) and global prefix options`, () => {
Reflect.set(routeInfoPathExtractor, 'prefixPath', '/:param');
Reflect.set(
routeInfoPathExtractor,
'excludedGlobalPrefixRoutes',
mapToExcludeRoute(['foo']),
);

expect(
routeInfoPathExtractor.extractPathsFrom({
path: '*',
method: RequestMethod.ALL,
}),
).to.eql(['/:param$', '/:param/*', '/foo$']);

expect(
routeInfoPathExtractor.extractPathsFrom({
path: '*',
method: RequestMethod.ALL,
version: '1',
}),
).to.eql(['/:param/v1$', '/:param/v1/*', '/v1/foo$']);

expect(
routeInfoPathExtractor.extractPathsFrom({
path: 'foo',
method: RequestMethod.ALL,
version: '1',
}),
).to.eql(['/v1/foo']);

expect(
routeInfoPathExtractor.extractPathsFrom({
path: 'bar',
method: RequestMethod.ALL,
version: '1',
}),
).to.eql(['/:param/v1/bar']);
});
});

describe('extractPathFrom', () => {
Expand Down
Loading