Skip to content

Commit

Permalink
docs: update swagger and add more case
Browse files Browse the repository at this point in the history
  • Loading branch information
czy88840616 committed Jul 6, 2024
1 parent 44ec49d commit 0299686
Show file tree
Hide file tree
Showing 6 changed files with 311 additions and 77 deletions.
139 changes: 139 additions & 0 deletions packages/swagger/test/__snapshots__/parser.test.ts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -320,6 +320,145 @@ exports[`test @ApiBody should test ApiBody with binary 1`] = `
}
`;

exports[`test @ApiBody should test ApiBody with contentType 1`] = `
{
"components": {
"schemas": {
"UploadType": {
"properties": {
"file": {
"description": "this is file test",
"format": "binary",
"type": "string",
},
"name": {
"description": "The name of the Cat",
"example": "Kitty",
"type": "string",
},
},
"type": "object",
},
},
},
"info": {
"contact": {},
"description": "",
"title": "",
"version": "1.0.0",
},
"openapi": "3.0.1",
"paths": {
"/api/update_user": {
"post": {
"description": undefined,
"operationId": "apicontroller_updateuser",
"parameters": [],
"requestBody": {
"content": {
"multipart/form-data": {
"schema": {
"$ref": "#/components/schemas/UploadType",
},
},
},
"description": undefined,
"required": true,
},
"responses": {
"200": {
"description": "OK",
},
},
"summary": undefined,
"tags": [
"api",
],
},
},
},
"servers": [],
"tags": [
{
"description": "api",
"externalDocs": undefined,
"name": "api",
},
],
}
`;

exports[`test @ApiBody should test ApiBody with contentType and files 1`] = `
{
"components": {
"schemas": {
"UploadType": {
"properties": {
"files": {
"items": {
"description": "this is file test",
"format": "binary",
"type": "string",
},
"type": "array",
},
"name": {
"description": "The name of the Cat",
"example": "Kitty",
"type": "string",
},
},
"type": "object",
},
},
},
"info": {
"contact": {},
"description": "",
"title": "",
"version": "1.0.0",
},
"openapi": "3.0.1",
"paths": {
"/api/update_user": {
"post": {
"description": undefined,
"operationId": "apicontroller_updateuser",
"parameters": [],
"requestBody": {
"content": {
"multipart/form-data": {
"schema": {
"$ref": "#/components/schemas/UploadType",
},
},
},
"description": undefined,
"required": true,
},
"responses": {
"200": {
"description": "OK",
},
},
"summary": undefined,
"tags": [
"api",
],
},
},
},
"servers": [],
"tags": [
{
"description": "api",
"externalDocs": undefined,
"name": "api",
},
],
}
`;

exports[`test @ApiBody should test ApiBody with example 1`] = `
{
"components": {
Expand Down
82 changes: 79 additions & 3 deletions packages/swagger/test/parser.test.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
import {
ApiAcceptedResponse,
ApiBadGatewayResponse,
ApiBadRequestResponse, ApiBasicAuth, ApiBearerAuth,
ApiBadRequestResponse,
ApiBasicAuth,
ApiBearerAuth,
ApiBody,
ApiConflictResponse, ApiCookieAuth,
ApiConflictResponse,
ApiCookieAuth,
ApiCreatedResponse,
ApiDefaultResponse,
ApiExcludeController,
Expand All @@ -23,7 +26,8 @@ import {
ApiNoContentResponse,
ApiNotAcceptableResponse,
ApiNotFoundResponse,
ApiNotImplementedResponse, ApiOAuth2,
ApiNotImplementedResponse,
ApiOAuth2,
ApiOkResponse,
ApiOperation, ApiParam,
ApiPayloadTooLargeResponse,
Expand All @@ -38,6 +42,7 @@ import {
ApiUnauthorizedResponse,
ApiUnprocessableEntityResponse,
ApiUnsupportedMediaTypeResponse,
BodyContentType,
getSchemaPath,
SwaggerExplorer,
Type,
Expand Down Expand Up @@ -603,6 +608,77 @@ describe('test @ApiBody', () => {
explorer.generatePath(APIController);
expect(explorer.getData()).toMatchSnapshot();
});

it('should test ApiBody with contentType', () => {
class UploadType {
@ApiProperty({ example: 'Kitty', description: 'The name of the Cat' })
name: string;

@ApiProperty({
type: 'string',
format: 'binary',
description: 'this is file test'
})
file: any;
}

@Controller('/api')
@ApiExtraModel(UploadType)
class APIController {
@Post('/update_user')
@ApiBody({
required: true,
contentType: BodyContentType.Multipart,
schema: {
type: UploadType,
}
})
async updateUser(@File() files: any) {
// ...
}
}

const explorer = new CustomSwaggerExplorer();
explorer.generatePath(APIController);
expect(explorer.getData()).toMatchSnapshot();
});

it('should test ApiBody with contentType and files', () => {
class UploadType {
@ApiProperty({ example: 'Kitty', description: 'The name of the Cat' })
name: string;

@ApiProperty({
type: 'array',
items: {
type: 'string',
format: 'binary',
description: 'this is file test'
}
})
files: any;
}

@Controller('/api')
@ApiExtraModel(UploadType)
class APIController {
@Post('/update_user')
@ApiBody({
required: true,
contentType: BodyContentType.Multipart,
schema: {
type: UploadType,
}
})
async updateUser(@Files() files: any) {
// ...
}
}

const explorer = new CustomSwaggerExplorer();
explorer.generatePath(APIController);
expect(explorer.getData()).toMatchSnapshot();
});
});

describe('test @ApiExtension', () => {
Expand Down
2 changes: 1 addition & 1 deletion site/docs/extensions/cache.md
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ export class UserService {
```typescript
await this.cacheManager.set(key, value, {ttl: 1000}); // ttl的单位为秒
```
如果你想要禁止 Cache 不过期,则将 TTL 设置为 null 即可。
如果你想要 Cache 不过期,则将 TTL 设置为 null 即可。
```typescript
await this.cacheManager.set(key, value, {ttl: null});
```
Expand Down
79 changes: 44 additions & 35 deletions site/docs/extensions/swagger.md
Original file line number Diff line number Diff line change
Expand Up @@ -432,71 +432,76 @@ async upateUser(@Body() dto: UserDTO) {

如需其他细节,请使用 `@ApiBody` 增强。

### 文件上传定义
注意,Swagger 规定,`Body` 定义只能存在一个,如果配置了 `@ApiBody` ,则类型提取的数据会自动被覆盖。

使用 ```@ApiBody``` 设置 `contentType`
比如下面示例中,`Body` 的类型会被替换为 `Cat`

```typescript
@Post('/:id', { summary: 'test'})
@ApiBody({
description: 'this is body',
contentType: BodyContentType.Multipart
type: Cat
})
@ApiParam({ description: 'this is id' })
async create(@Body() createCatDto: CreateCatDto, @Param('id') id: number): Promise<Cat> {
return this.catsService.create(createCatDto);
async upateUser(@Body() dto: UserDTO) {
// ...
}
```



`CreateCatDto` 中使用 `@ApiProperty` 添加 `format`

```typescript
@ApiProperty({
type: 'string',
format: 'binary',
description: 'this is file test'
})
file: any;
```
### 文件上传定义

Swagger UI 中展示:
![swagger4](https://img.alicdn.com/imgextra/i3/O1CN01KlDHNt24mMglN1fyH_!!6000000007433-0-tps-1598-434.jpg)
文件上传是 Post 请求中较为特殊的一类场景。

:::caution
可以通过在 DTO 中定义属性来实现多个文件以及 `Fields` 的类型。

如需 swagger 展示上传信息,请务必添加类型(装饰器对应的类型,以及 @ApiBody 中的 type),否则会报错。
```typescript
import { ApiProperty, BodyContentType } from "@midwayjs/swagger";

:::
export class CreateCatDto {
// ...
@ApiProperty({
type: 'array',
items: {
type: 'string',
format: 'binary',
}
})
files: any;
}

兼容 Upload 组件,添加 ```@ApiBody()``` 装饰器描述
// ...

```typescript
@Post('/test')
@ApiBody({ description: 'hello file' })
@ApiBody({ description: 'hello fields', type: Cat })
async upload(@File() f: any, @Fields() data: Cat) {
@Post('/test1')
@ApiBody({
contentType: BodyContentType.Multipart,
schema: {
type: CreateCatDto,
}
})
async upload1(@Files() files, @Fields() fields) {
// ...
}
```

Swagger UI 中展示:
![swagger5](https://img.alicdn.com/imgextra/i2/O1CN01icnwZE24OY5vdkkKx_!!6000000007381-0-tps-1272-1026.jpg)
![swagger6](https://img.alicdn.com/imgextra/i3/O1CN01w9dZxe1YQJv3uOycZ_!!6000000003053-0-tps-1524-1118.jpg)

不添加 ```@ApiBody()``` 装饰器描述
如果不需要多个文件,使用 schema 定义即可。

```typescript
@Post('/test1')
async upload1(@Files() f: any[], @Fields() data: Cat) {
export class CreateCatDto {
// ...
@ApiProperty({
type: 'string',
format: 'binary',
})
file: any;
}
```

Swagger UI 中展示:
![swagger4](https://img.alicdn.com/imgextra/i3/O1CN01KlDHNt24mMglN1fyH_!!6000000007433-0-tps-1598-434.jpg)


Swagger UI 中展示:
![swagger6](https://img.alicdn.com/imgextra/i3/O1CN01w9dZxe1YQJv3uOycZ_!!6000000003053-0-tps-1524-1118.jpg)

### 请求 Header

Expand Down Expand Up @@ -687,6 +692,10 @@ async findOne(@Param('id') id: string, @Query('test') test: any): ViewCat {



## 更多的定义示例

Swagger 中还有更多的写法,框架都进行了支持,更多用法可以查看我们的 [测试用例](https://github.com/midwayjs/midway/blob/main/packages/swagger/test/parser.test.ts)



## 更多配置
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ You can also manually set TTL (Expiration Time), as follows:
```typescript
Await this.cacheManager.set(key, value, {ttl: 1000}); // ttl is in seconds
```
If you want to prohibit Cache from expiring, set TTL to null.
If you don't want to Cache expired, set TTL to null.
```typescript
await this.cacheManager.set(key, value, {ttl: null});
```
Expand Down
Loading

0 comments on commit 0299686

Please sign in to comment.