diff --git a/README.md b/README.md index 08e0ea7..b5d125b 100644 --- a/README.md +++ b/README.md @@ -230,6 +230,30 @@ GET http://localhost:3000/users/99 → 404 { statusCode: 404, message: 'Use POST http://localhost:3000/users → { id: '2', name: '...' } ``` +### Wildcard routes + +The Express adapter supports terminal wildcards with the same behavior on +Express 4 and Express 5. Use an anonymous wildcard when the default parameter +name `wildcard` is sufficient, or append a name after `*`: + +```ts +@Controller('files') +export class FilesController { + @On('get', '/*filepath') + findFile(@Param('filepath') filepath: string) { + return { filepath } + } +} +``` + +`GET /files/images/avatar.png` sets `filepath` to +`'images/avatar.png'`. Wildcards must be the final part of a route and may span +multiple path segments. `@On('get', '*')` and `@On('get', '/*')` create a +controller-wide catch-all and expose the matched value as `@Param('wildcard')`. + +Concrete routes are registered before wildcard routes, so a route such as +`/health` takes precedence over `/*path` regardless of declaration order. + ## Packages | Package | Description | diff --git a/packages/platform-express/src/adapters/express.handler.registry.ts b/packages/platform-express/src/adapters/express.handler.registry.ts index ba812cf..31400ce 100644 --- a/packages/platform-express/src/adapters/express.handler.registry.ts +++ b/packages/platform-express/src/adapters/express.handler.registry.ts @@ -4,6 +4,7 @@ import { GuardRejectionError, HttpException, HandlerMetadata, LunaHandler } from import { ExpressHandler } from '../types' import { HttpExceptionResponse } from '../exceptions' +import { compileExpressRoutePath } from '../routing/express-route-path' type HttpMethod = 'get' | 'post' | 'put' | 'patch' | 'delete' | 'options' | 'head' @@ -25,7 +26,15 @@ export class ExpressHandlerRegistry { private readonly handlers: ExpressHandler[] = [] register(handler: LunaHandler, metadata: HandlerMetadata): void { - this.handlers.push({ handler, metadata }) + const entry = { handler, metadata } + if (metadata.path.includes('*')) { + this.handlers.push(entry) + return + } + + const firstWildcard = this.handlers.findIndex(({ metadata: item }) => item.path.includes('*')) + if (firstWildcard === -1) this.handlers.push(entry) + else this.handlers.splice(firstWildcard, 0, entry) } getHandlers(): ExpressHandler[] { @@ -39,7 +48,13 @@ export class ExpressHandlerRegistry { const router = Router() const middleware = this.uploadMiddleware(metadata.uploadField) - router[event as HttpMethod](path, ...middleware, this.buildRoute(handler, metadata.successStatusCode)) + const route = compileExpressRoutePath(path) + router[event as HttpMethod]( + route.path, + ...route.paramsMiddleware, + ...middleware, + this.buildRoute(handler, metadata.successStatusCode), + ) app.use(`/${prefix}`, router) } } diff --git a/packages/platform-express/src/routing/express-route-path.ts b/packages/platform-express/src/routing/express-route-path.ts new file mode 100644 index 0000000..c584014 --- /dev/null +++ b/packages/platform-express/src/routing/express-route-path.ts @@ -0,0 +1,71 @@ +import { RequestHandler } from 'express' + +export interface ExpressRoutePath { + path: string | RegExp + paramsMiddleware: RequestHandler[] + isWildcard: boolean +} + +const PARAM_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/ + +function escapeRegExp(value: string): string { + return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') +} + +/** + * Compiles Luna's terminal wildcard syntax to a RegExp accepted by Express 4 + * and Express 5. Captures are copied from Express's numeric RegExp params to + * stable named params before the route handler runs. + */ +export function compileExpressRoutePath(path: string): ExpressRoutePath { + if (!path.includes('*')) return { path, paramsMiddleware: [], isWildcard: false } + + const normalized = path === '*' ? '/*' : path + const wildcardMatches = [...normalized.matchAll(/\*/g)] + const wildcardIndex = wildcardMatches[0]?.index ?? -1 + + if (wildcardMatches.length !== 1 || wildcardIndex < 0) { + throw new Error(`ExpressAdapter: route "${path}" must contain exactly one wildcard`) + } + + const wildcardName = normalized.slice(wildcardIndex + 1) || 'wildcard' + if (!PARAM_NAME.test(wildcardName)) { + throw new Error(`ExpressAdapter: wildcard in route "${path}" must be terminal and optionally named`) + } + + const prefix = normalized.slice(0, wildcardIndex) + const paramNames: string[] = [] + let source = '' + + for (const segment of prefix.split('/')) { + if (!segment) continue + source += '/' + if (segment.startsWith(':')) { + const name = segment.slice(1) + if (!PARAM_NAME.test(name)) { + throw new Error(`ExpressAdapter: unsupported parameter segment "${segment}" in wildcard route "${path}"`) + } + paramNames.push(name) + source += '([^/]+)' + } else { + source += escapeRegExp(segment) + } + } + + const isRootWildcard = prefix === '/' + if (isRootWildcard) source = '' + paramNames.push(wildcardName) + source += isRootWildcard ? '/(.*)' : '/(.+)' + + const route = new RegExp(`^${source}/?$`) + const paramsMiddleware: RequestHandler = (request, _response, next) => { + const captures = paramNames.map((_name, index) => request.params[String(index)]) + for (const [index, name] of paramNames.entries()) { + request.params[name] = captures[index] + delete request.params[String(index)] + } + next() + } + + return { path: route, paramsMiddleware: [paramsMiddleware], isWildcard: true } +} diff --git a/packages/platform-express/tests/integration/wildcard.integration.spec.ts b/packages/platform-express/tests/integration/wildcard.integration.spec.ts new file mode 100644 index 0000000..ac739cb --- /dev/null +++ b/packages/platform-express/tests/integration/wildcard.integration.spec.ts @@ -0,0 +1,66 @@ +import 'reflect-metadata' +import { Injectable, Module } from '@lunafw/core' +import { Controller, LunaFactory, On, Param } from '@lunafw/common' + +import { ExpressAdapter } from '../../src' + +@Injectable() +@Controller('files') +class FileController { + @On('get', '/health') + health() { + return { status: 'ok' } + } + + @On('get', '/*filepath') + file(@Param('filepath') filepath: string) { + return { filepath } + } +} + +@Injectable() +@Controller() +class FallbackController { + @On('get', '*') + fallback(@Param('wildcard') wildcard: string) { + return { wildcard } + } +} + +@Module({ providers: [FileController, FallbackController] }) +class AppModule {} + +describe('Express wildcard routes', () => { + let adapter: ExpressAdapter + let baseUrl: string + + beforeAll(async () => { + adapter = new ExpressAdapter({ port: 0 }) + const app = await LunaFactory.createApplication(AppModule, adapter) + await app.start() + baseUrl = `http://localhost:${adapter.getPort()}` + }) + + afterAll(async () => { + await adapter.close() + }) + + it('exposes a named multi-segment wildcard through @Param', async () => { + const response = await fetch(`${baseUrl}/files/images/avatars/user.png`) + + expect(response.status).toBe(200) + expect(await response.json()).toEqual({ filepath: 'images/avatars/user.png' }) + }) + + it('keeps concrete routes ahead of wildcard routes', async () => { + const response = await fetch(`${baseUrl}/files/health`) + + expect(await response.json()).toEqual({ status: 'ok' }) + }) + + it('supports an anonymous application-wide fallback', async () => { + const response = await fetch(`${baseUrl}/missing/nested/path`) + + expect(await response.json()).toEqual({ wildcard: 'missing/nested/path' }) + }) +}) diff --git a/packages/platform-express/tests/unit/express-route-path.spec.ts b/packages/platform-express/tests/unit/express-route-path.spec.ts new file mode 100644 index 0000000..5e938a4 --- /dev/null +++ b/packages/platform-express/tests/unit/express-route-path.spec.ts @@ -0,0 +1,35 @@ +import { compileExpressRoutePath } from '../../src/routing/express-route-path' + +describe('compileExpressRoutePath', () => { + it('leaves ordinary Express paths unchanged', () => { + const route = compileExpressRoutePath('/:id') + + expect(route.path).toBe('/:id') + expect(route.paramsMiddleware).toEqual([]) + expect(route.isWildcard).toBe(false) + }) + + it.each(['*', '/*'])('compiles the root wildcard %s', (path) => { + const route = compileExpressRoutePath(path) + + expect(route.path).toBeInstanceOf(RegExp) + expect((route.path as RegExp).test('/')).toBe(true) + expect((route.path as RegExp).test('/images/avatar.png')).toBe(true) + }) + + it('compiles a named terminal wildcard and preceding params', () => { + const route = compileExpressRoutePath('/users/:id/files/*filepath') + const pattern = route.path as RegExp + + expect(pattern.exec('/users/42/files/avatar/photo.png')?.slice(1)).toEqual([ + '42', + 'avatar/photo.png', + ]) + expect(pattern.test('/users/42/files')).toBe(false) + }) + + it.each(['/files/*/edit', '/files/**', '/files/*bad-name'])( + 'rejects invalid wildcard syntax: %s', + (path) => expect(() => compileExpressRoutePath(path)).toThrow('ExpressAdapter:'), + ) +})