CV肉饼王

Talk is cheap. Show me the code.

0%

Nestjs 使用 Swagger 生成接口文档

1.安装依赖
1
npm install --save @nestjs/swagger swagger-ui-express
2.配置swagger
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// src/main.ts

import { ValidationPipe } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { HttpExceptionFilter } from './filters/http-exception.filter';
import { TransformInterceptor } from './interceptor/transform.interceptor';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';

async function bootstrap() {
const app = await NestFactory.create(AppModule);

app.useGlobalPipes(new ValidationPipe())
app.useGlobalInterceptors(new TransformInterceptor())
app.useGlobalFilters(new HttpExceptionFilter())

const options = new DocumentBuilder()
.setTitle('blog-serve')
.setDescription('接口文档')
.setVersion('1.0')
.build();
const document = SwaggerModule.createDocument(app, options);
SwaggerModule.setup('swagger-doc', app, document);

await app.listen(3000);
}
bootstrap();
3.设置nest-cli.json
1
2
3
4
5
6
7
8
9
10
11
12
13
14
{
"collection": "@nestjs/schematics",
"sourceRoot": "src",
"compilerOptions": {
"plugins": [
{
"name": "@nestjs/swagger",
"options": {
"introspectComments": true
}
}
]
}
}
4.修改dto,添加文档说明
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import { IsNotEmpty, IsOptional } from 'class-validator';
import { IdDTO } from './id.dto';

export class ArticleEditDTO extends IdDTO {
/**
* 文章标题
* @example 美丽的大海
*/
@IsOptional()
@IsNotEmpty({ message: '请输入文章标题' })
readonly title?: string;

/**
* 文章描述
* @example 给你讲述美丽的大海
*/
@IsOptional()
@IsNotEmpty({ message: '请输入文章描述' })
readonly description?: string;

/**
* 文章内容
* @example 美丽的大海,你是如此美丽
*/
@IsOptional()
@IsNotEmpty({ message: '请输入文章内容' })
readonly content?: string;
}
5.查看
1
localhost:3000/swagger-doc

参考文章:

使用 Swagger 生成文档

Nestjs-CLI Plugin

Nestjs-Open API

Nestjs-Swagger sample

blog-serve