## 操作
在OpenAPI規范中,API暴露的以{資源}為結束的終端,例如`/users`或者`/reports/summary`,都是可以執行HTTP方法的,例如`GET`,`POST`或者`DELETE`。
### 標簽
要為控制器附加一個標簽,使用`@ApiTags(...tags)裝飾器。
```TypeScript
@ApiTags('cats')
@Controller('cats')
export class CatsController {}
```
### 標頭
要作為請求的一部分定義自定義標頭,使用`@ApiHeader()`裝飾器。
```TypeScript
@ApiHeader({
name: 'X-MyHeader',
description: 'Custom header',
})
@Controller('cats')
export class CatsController {}
```
### 響應
要定義一個自定義響應, 使用`@ApiResponse()裝飾器.
```TypeScript
@Post()
@ApiResponse({ status: 201, description: 'The record has been successfully created.'})
@ApiResponse({ status: 403, description: 'Forbidden.'})
async create(@Body() createCatDto: CreateCatDto) {
this.catsService.create(createCatDto);
}
```
Nest提供了一系列繼承自@ApiResponse裝飾器的用于速記的API響應裝飾器:
- @ApiOkResponse()
- @ApiCreatedResponse()
- @ApiAcceptedResponse()
- @ApiNoContentResponse()
- @ApiMovedPermanentlyResponse()
- @ApiBadRequestResponse()
- @ApiUnauthorizedResponse()
- @ApiNotFoundResponse()
- @ApiForbiddenResponse()
- @ApiMethodNotAllowedResponse()
- @ApiNotAcceptableResponse()
- @ApiRequestTimeoutResponse()
- @ApiConflictResponse()
- @ApiTooManyRequestsResponse()
- @ApiGoneResponse()
- @ApiPayloadTooLargeResponse()
- @ApiUnsupportedMediaTypeResponse()
- @ApiUnprocessableEntityResponse()
- @ApiInternalServerErrorResponse()
- @ApiNotImplementedResponse()
- @ApiBadGatewayResponse()
- @ApiServiceUnavailableResponse()
- @ApiGatewayTimeoutResponse()
- @ApiDefaultResponse()
```TypeScript
@Post()
@ApiCreatedResponse({ description: 'The record has been successfully created.'})
@ApiForbiddenResponse({ description: 'Forbidden.'})
async create(@Body() createCatDto: CreateCatDto) {
this.catsService.create(createCatDto);
}
```
要從請求返回一個指定的模型,需要創建一個類并用`@ApiProperty()`裝飾器注釋它。
```TypeScript
export class Cat {
@ApiProperty()
id: number;
@ApiProperty()
name: string;
@ApiProperty()
age: number;
@ApiProperty()
breed: string;
}
```
`Cat`模型可以與響應裝飾器的`type`屬性組合使用。
```TypeScript
@ApiTags('cats')
@Controller('cats')
export class CatsController {
@Post()
@ApiCreatedResponse({
description: 'The record has been successfully created.',
type: Cat,
})
async create(@Body() createCatDto: CreateCatDto): Promise<Cat> {
return this.catsService.create(createCatDto);
}
}
```
打開瀏覽器確認生成的`Cat`模型。

### 文件上傳
使用`@ApiBody`裝飾器和`@ApiConsumes()`來使能文件上傳,這里有一個完整的使用[文件上傳](https://docs.nestjs.com/techniques/file-upload)技術的例子。
```TypeScript
@UseInterceptors(FileInterceptor('file'))
@ApiConsumes('multipart/form-data')
@ApiBody({
description: 'List of cats',
type: FileUploadDto,
})
uploadFile(@UploadedFile() file) {}
```
`FileUploadDto`像這樣定義:
```TypeScript
class FileUploadDto {
@ApiProperty({ type: 'string', format: 'binary' })
file: any;
}
```
要處理多個文件上傳,如下定義`FilesUploadDto`:
```TypeScript
class FilesUploadDto {
@ApiProperty({ type: 'array', items: { type: 'string', format: 'binary' } })
files: any[];
}
```
### 擴展
要為請求增加一個擴展使用`@ApiExtension()`裝飾器. 該擴展名稱必須以 `x-`前綴。
```TypeScript
@ApiExtension('x-foo', { hello: 'world' })
```
### 高級主題:通用`ApiResponse`
基于[原始定義](https://docs.nestjs.com/openapi/types-and-parameters#raw-definitions),的能力,我們可以為Swagger定義通用原型:
```TypeScript
export class PaginatedDto<TData> {
@ApiProperty()
total: number;
@ApiProperty()
limit: number;
@ApiProperty()
offset: number;
results: TData[];
}
```
我們跳過了定義`results`,因為后面要提供一個原始定義。現在,我們定義另一個DTO,例如`CatDto`如下:
```TypeScript
export class CatDto {
@ApiProperty()
name: string;
@ApiProperty()
age: number;
@ApiProperty()
breed: string;
}
```
我們可以定義一個`PaginatedDto<CatDto>`響應如下:
```TypeScript
@ApiOkResponse({
schema: {
allOf: [
{ $ref: getSchemaPath(PaginatedDto) },
{
properties: {
results: {
type: 'array',
items: { $ref: getSchemaPath(CatDto) },
},
},
},
],
},
})
async findAll(): Promise<PaginatedDto<CatDto>> {}
```
在這個例子中,我們指定響應擁有所有的`PaginatedDto`并且`results`屬性類型為`CatDto`數組。
- `getSchemaPath()` 函數從一個給定模型的OpenAPI指定文件返回OpenAPI原型路徑
- `allOf`是一個OAS3的概念,包括各種各樣相關用例的繼承。
最后,因為`PaginatedDto`沒有被任何控制器直接引用,`SwaggerModule`還不能生成一個相應的模型定義。我們需要一個[額外的模型](https://docs.nestjs.com/openapi/types-and-parameters#extra-models),可以在控制器水平使用`@ApiExtraModels()`裝飾器。
```TypeScript
@Controller('cats')
@ApiExtraModels(PaginatedDto)
export class CatsController {}
```
如果你現在運行Swagger,為任何終端生成的`swagger.json`文件看上去應該像定義的這樣:
```JSON
"responses": {
"200": {
"description": "",
"content": {
"application/json": {
"schema": {
"allOf": [
{
"$ref": "#/components/schemas/PaginatedDto"
},
{
"properties": {
"results": {
"$ref": "#/components/schemas/CatDto"
}
}
}
]
}
}
}
}
}
```
為了讓其可重用,我們為`PaginatedDto`像這樣創建一個裝飾器:
```TypeScript
export const ApiPaginatedResponse = <TModel extends Type<any>>(
model: TModel,
) => {
return applyDecorators(
ApiOkResponse({
schema: {
allOf: [
{ $ref: getSchemaPath(PaginatedDto) },
{
properties: {
results: {
type: 'array',
items: { $ref: getSchemaPath(model) },
},
},
},
],
},
}),
);
};
```
> `Type<any>`接口和`applyDecorators`函數從`@nestjs/common`引入.
我們現在可以為終端使用自定義的`@ApiPaginatedResponse()`裝飾器 :
```TypeScript
@ApiPaginatedResponse(CatDto)
async findAll(): Promise<PaginatedDto<CatDto>> {}
```
作為客戶端生成工具,這一方法為客戶端提供了一個含糊的`PaginatedResponse<TModel>`。下面示例展示了生成的客戶端訪問`GET /`終端的結果。
```TypeScript
// Angular
findAll(): Observable<{ total: number, limit: number, offset: number, results: CatDto[] }>
```
可以看出,這里的返回類型是含糊不清的。要處理這個問題,可以為`ApiPaginatedResponse`的`原型`添加`title`屬性。
```TypeScript
export const ApiPaginatedResponse = <TModel extends Type<any>>(model: TModel) => {
return applyDecorators(
ApiOkResponse({
schema: {
title: `PaginatedResponseOf${model.name}`
allOf: [
// ...
],
},
}),
);
};
```
現在結果變成了。
```TypeScript
// Angular
findAll(): Observable<PaginatedResponseOfCatDto>
```
- 介紹
- 概述
- 第一步
- 控制器
- 提供者
- 模塊
- 中間件
- 異常過濾器
- 管道
- 守衛
- 攔截器
- 自定義裝飾器
- 基礎知識
- 自定義提供者
- 異步提供者
- 動態模塊
- 注入作用域
- 循環依賴
- 模塊參考
- 懶加載模塊
- 應用上下文
- 生命周期事件
- 跨平臺
- 測試
- 技術
- 數據庫
- Mongo
- 配置
- 驗證
- 緩存
- 序列化
- 版本控制
- 定時任務
- 隊列
- 日志
- Cookies
- 事件
- 壓縮
- 文件上傳
- 流式處理文件
- HTTP模塊
- Session(會話)
- MVC
- 性能(Fastify)
- 服務器端事件發送
- 安全
- 認證(Authentication)
- 授權(Authorization)
- 加密和散列
- Helmet
- CORS(跨域請求)
- CSRF保護
- 限速
- GraphQL
- 快速開始
- 解析器(resolvers)
- 變更(Mutations)
- 訂閱(Subscriptions)
- 標量(Scalars)
- 指令(directives)
- 接口(Interfaces)
- 聯合類型
- 枚舉(Enums)
- 字段中間件
- 映射類型
- 插件
- 復雜性
- 擴展
- CLI插件
- 生成SDL
- 其他功能
- 聯合服務
- 遷移指南
- Websocket
- 網關
- 異常過濾器
- 管道
- 守衛
- 攔截器
- 適配器
- 微服務
- 概述
- Redis
- MQTT
- NATS
- RabbitMQ
- Kafka
- gRPC
- 自定義傳輸器
- 異常過濾器
- 管道
- 守衛
- 攔截器
- 獨立應用
- Cli
- 概述
- 工作空間
- 庫
- 用法
- 腳本
- Openapi
- 介紹
- 類型和參數
- 操作
- 安全
- 映射類型
- 裝飾器
- CLI插件
- 其他特性
- 遷移指南
- 秘籍
- CRUD 生成器
- 熱重載
- MikroORM
- TypeORM
- Mongoose
- 序列化
- 路由模塊
- Swagger
- 健康檢查
- CQRS
- 文檔
- Prisma
- 靜態服務
- Nest Commander
- 問答
- Serverless
- HTTP 適配器
- 全局路由前綴
- 混合應用
- HTTPS 和多服務器
- 請求生命周期
- 常見錯誤
- 實例
- 遷移指南
- 發現
- 誰在使用Nest?