Introduction to the
The OpenAPI(Swagger) specification is a powerful definition format for describing RESTful apis. It can generate interface documents in various formats, generate client and server code in multiple languages, and online interface debugging pages, and so on. Reduces the cost of front and back end communication.
The installation
Nest.js provides a special module to use it, which we can install directly in the project using instructions
# yarn
yarn add @nestjs/swagger swagger-ui-express
# npm
npm install --save @nestjs/swagger swagger-ui-express
Copy the code
Bootstrap initialization
After successful installation, we need to open main.ts to initialize Swagger, add the following code to main.ts
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.setGlobalPrefix('api');
const options = new DocumentBuilder()
/ / title
.setTitle('vite-app-api')
/ / description
.setDescription('Server application built with NestJs')
/ / version number
.setVersion('1.0')
// The tag is not needed here
// .addTag('cats')
.build();
const document = SwaggerModule.createDocument(app, options);
// Since we have left the API prefix for interface, change it to api-docs
SwaggerModule.setup('api-docs', app, document);
await app.listen(8081);
}
bootstrap();
Copy the code
To start the project, visit first
As you can see, the current interface in our project has been scanned. However, the interface description is currently empty. I need to add it manually here
configuration
interface
First, we need to classify interfaces according to services and label them accordingly. Open the user. The controller. Ts
@Controller('user')
// Add a label to the controller here
@ApiTags('User action')
export class UserController {
constructor(private readonly userService: UserService) {}
@Post('register')
register(@Body() user: any) {
return this.userService.register(user); }}Copy the code
To see a swagger
This distinction is very convenient for debugging and maintenance
parameter
First of all, to add the type of the input parameter, as anyone who has looked at the documentation will see, they recommend using class instead of interface to define the type. Here’s what the original quote says:
First (if you use TypeScript), we need to determine the DTO (Data Transfer Object) schema. A DTO is an object that defines how data is sent across a network. DTO patterns can be defined using TypeScript interfaces or simple classes. Interestingly, we recommend using classes here. Why is that? Classes are part of the JavaScript ES6 standard, so they are retained as actual entities in compiled JavaScript. On the other hand, because TypeScript interfaces are removed during the transformation, Nest cannot reference them at run time. This is important because features such as pipes provide more possibilities for accessing a variable’s metatype at run time.
We create a new types folder under SRC and create a system-user.to.ts file
import { ApiProperty } from '@nestjs/swagger';
export class RegisterUserDto {
// Add a description to the parameter
@ApiProperty({ description: 'Username' })
userName: string;
@ApiProperty({ description: 'password' })
pwd: string;
@ApiProperty({ description: 'Confirm password' })
confirmPwd: string;
}
Copy the code
And then we introduce and apply it in our controller.
// user.controller.ts
import { RegisterUserDto } from '@/types/system-user.dto'; // configure path alias. // configure path alias
@Controller('user')
@ApiTags('User action')
export class UserController {
constructor(private readonly userService: UserService) {}
@Post('register')
// Use this decorator to add the interface description
@ApiOperation({ summary: 'Register a new user' })
register(@Body() user: RegisterUserDto): boolean {
return this.userService.register(user); }}Copy the code
Look at the web page again
Swagger generates interface input parameter description and sample data for us, we can also directly test the interface here
Click Try It Out and it will send the request to the interface with the sample data, although you can customize the data here as well
The curl, request URL, and corresponding body are displayed.
- to be continued~~