Decorator
Decorator
TypeScript 中的常见的装饰器类型有 5 种,包括类装饰器、方法装饰器、属性装饰器、参数装饰器和访问器装饰器。
在 Nest 中实现了前 4 种装饰器:
- 类装饰器:
@Controller、@Injectable、@Module、@UseInterceptors等。 - 方法装饰器:
@Get、@Post、@Patch、@Delete、@UseInterceptors等。 - 属性装饰器:
@IsNotEmpty、@IsString、@IsNumber等。 - 参数装饰器:
@Body、@Param、@Query等。
常用的装饰器作用如下:
@Controller():用于装饰控制器类,使之能够管理应用中的路由程序,并通过设置路由路径前缀来模块化管理路由。@Injectable():装饰后成为服务提供者(provider),可以被其他对象进行依赖注入。@Module():模块装饰器,用于在Nest中划分功能模块并限制依赖注入的范围。@UseInterceptors():用于绑定拦截器,也可以作用在类方法上,AOP相关的装饰器都与之类似,比如@UseFilters()、@UsePipes()等。@Global():声明全局模块。@Get、@Post、@Put、@Delete、@Patch、@Options、@Head:HTTP 请求方式。
基本用法
@Param 和 @Query 是 GET 方式的请求,只是 url 处理不一样:
@Controller('user')
export class UserController {
constructor(private readonly userService: UserService) {}
@Get('find')
query(@Query('name') name: string, @Query('age') age: number) {
return this.userService.query(name, age);
}
@Get(':id')
findOne(@Param('id') id: string) {
return this.userService.findOne(+id);
}
}
@Body 装饰器处理 POST 请求,通常Content-Type 为:
x-www-form-urlencoded。application/json。
Nest 会解析请求体,然后注入到 dto 中:
// create-user.dto.ts
export class CreateUserDto {
name: string;
age: number;
}
// user.controller.ts
@Controller('user')
export class UserController {
constructor(private readonly userService: UserService) {}
@Post()
create(@Body() createUserDto: CreateUserDto) {
return this.userService.create(createUserDto);
}
}
除此之外,还还可通过参数装饰器获取一些其他的信息:
@Get('other')
other(
@Ip() ip: string,
@Headers() headers: Record<string, any>,
@Req() request: Request,
@Res() response: Response,
) {
console.log(ip);
console.log(headers);
console.log(request.url);
response.end('other');
}
如果手动加入了响应对象,那么就必须通过响应对象处理返回信息,比如,上面的方法如果我们手动加上了 @Res,直接请求就会出现问题。