Files
smartserve/ts/decorators/decorators.route.ts
2025-11-29 15:24:00 +00:00

46 lines
1.2 KiB
TypeScript

/**
* @Route class decorator
* Marks a class as a controller with a base path
*/
import type { IRouteOptions } from '../core/smartserve.interfaces.js';
import { setBasePath, normalizePath } from './decorators.metadata.js';
import { ControllerRegistry } from './decorators.registry.js';
/**
* @Route decorator - marks a class as a route controller
*
* @example
* ```typescript
* @Route('/api/users')
* class UserController {
* @Get('/:id')
* getUser(ctx: IRequestContext) { ... }
* }
* ```
*/
export function Route(pathOrOptions?: string | IRouteOptions) {
return function <TClass extends new (...args: any[]) => any>(
target: TClass,
context: ClassDecoratorContext<TClass>
): TClass {
if (context.kind !== 'class') {
throw new Error('@Route can only decorate classes');
}
const path = typeof pathOrOptions === 'string'
? pathOrOptions
: pathOrOptions?.path ?? '';
// Store base path in metadata
setBasePath(target, path);
// Register controller after class initialization
context.addInitializer(function (this: TClass) {
ControllerRegistry.registerClass(target);
});
return target;
};
}