NestJS 是围绕 TypeScript 装饰器 构建的——特殊的 @ 前缀注解,用于将 元数据 附加到类、方法和参数上。NestJS 通过反射读取这些元数据,以声明式地配置路由、依赖注入、验证等功能。在 NestJS 中到处都是装饰器。
类装饰器 — 定义类的角色
ts
()
{}
()
{}
({ ... })
{}
类装饰器声明一个类在 NestJS 架构中 是什么(控制器、提供者、模块),并对其进行配置。
@Get() // GET request handler
@Post() // POST handler
@Get(":id") // GET /users/:id
@HttpCode(204) // set the response status code
@UseGuards(AuthGuard) // apply a guard to this route
@UseInterceptors(LoggingInterceptor)
findAll() {}
findOne(
@Param("id") id: string, // route parameter
@Query("sort") sort: string, // query string
@Body() dto: CreateUserDto, // request body
@Headers("auth") auth: string, // header
) {}
参数装饰器以声明式的方式从请求中提取您需要的数据——无需手动解析 req。
export class CreateUserDto {
@IsEmail() // validation rules (class-validator)
email: string;
@IsString()
@MinLength(8)
password: string;
}
Decorators attach METADATA that NestJS reads at runtime (via reflection) to:
✓ Register routes (@Get, @Controller)
✓ Wire dependency injection (@Injectable, @Inject)
✓ Apply guards/interceptors/pipes (@UseGuards, etc.)
✓ Validate input (@IsEmail, @IsString)
→ Behavior is declared WHERE it applies, concisely and readably.
// you can create your own — e.g. extract the current user from the request
export const CurrentUser = createParamDecorator((data, ctx) =>
ctx.switchToHttp().getRequest().user
);
// usage: findProfile(@CurrentUser() user: User) {}
装饰器是 NestJS 的标志性语法特性——整个框架围绕它们组织,因此理解它们的工作原理对于阅读和编写任何 NestJS 代码至关重要。
它们提供了一种 声明式、元数据驱动的方法:与其采用命令式配置,不如直接在类、方法和参数上添加注解来声明路由(@Controller、@Get)、依赖注入(@Injectable)、横切行为(@UseGuards、@UseInterceptors)和验证(@IsEmail)——简洁而易读。
这种元数据反射机制(与 Angular 和 Java/Spring 注解背后的思想相同)使 NestJS 能够拥有简洁、结构化的风格。
识别装饰器的类别(类、方法、参数、属性装饰器),了解常见的装饰器,并能够创建自定义装饰器是 NestJS 基本能力——装饰器是几乎每个功能的表达方式,使它们成为框架中首先要理解的最重要的东西之一。