swagger集成
In this article, we will integrate Swagger with a RESTful API built using NestJS. As a quick refresher, NestJS is a server-side web framework that supports both TypeScript and JavaScript. It brings an opinionated architecture to building a Node.js backend that is inspired by the Angular ecosystem. For more information, check out this introduction to NestJS.
在本文中,我们将Swagger与使用NestJS构建的RESTful API集成在一起。 作为快速更新,NestJS是一个服务器端Web框架,同时支持TypeScript和JavaScript。 它为基于Angular生态系统的Node.js后端构建了一个自以为是的体系结构。 有关更多信息, 请查看NestJS简介 。
On the other hand, Swagger is a tool for implementing the OpenAPI specification. The goal of the OpenAPI specification is to provide a standardized way to understand the capabilities of an API service without actual access to the source code. On the whole, Swagger is a tremendously helpful documentation tool for any modern web backend that exposes a RESTful API. More than just documentation, the OpenAPI specification served up by Swagger can be used to autogenerate servers/clients, facilitate automated testing, and much more.
另一方面, Swagger是用于实现OpenAPI规范的工具。 OpenAPI规范的目标是提供一种无需实际访问源代码即可了解API服务功能的标准化方法。 总体而言,Swagger对于公开了RESTful API的任何现代Web后端都是非常有用的文档工具。 Swagger提供的OpenAPI规范不只是文档,还可以用于自动生成服务器/客户端,促进自动化测试等等。
In the following sections, we’ll add Swagger to a basic RESTful API built using NestJS.
在以下各节中,我们将Swagger添加到使用NestJS构建的基本RESTful API中。
最初设定 (Initial Setup)
The first dependency that we’ll need is the NestJS CLI. Go ahead and install it globally by running npm install -g @nestjs/cli
. Once this is in place, bootstrap a new NestJS project using the CLI command nest new nestjs-with-swagger
. At this point, we should have a boilerplate NestJS project setup with a module, controller, and service.
我们需要的第一个依赖项是NestJS CLI 。 继续并通过运行npm install -g @nestjs/cli
全局npm install -g @nestjs/cli
。 安装到位后,使用CLI命令nest new nestjs-with-swagger
引导新的NestJS项目。 在这一点上,我们应该有一个带有模块,控制器和服务的样板NestJS项目设置。
We’ll now create a simple task tracking application by adding a new module for handling tasks and a few other files, as shown below:
现在,我们将通过添加一个用于处理任务的新模块和一些其他文件来创建一个简单的任务跟踪应用程序,如下所示:
@Controller('task')
export class TaskController {
constructor(private readonly taskService: TaskService) { }
@Get()
getTasks(): Task[] {
return this.taskService.getTasks();
}
@Get(':id')
getTask(@Param('id') taskId: string): Task {
return this.taskService.getTask(taskId);
}
@Post()
createTask(@Body() createTask: CreateTask): Task {
return this.taskService.createTask(createTask)
}
}
@Injectable()
export class TaskService {
private tasks: Task[] = [];
createTask(createTask: CreateTask): Task {
const { title, description } = createTask;
const newTask: Task = {
id: uuidv4(),
title,
description,
dateTimeCreated: moment().format(),
}
this.tasks.push(newTask)
return newTask;
}
getTasks(): Task[] {
return this.tasks;
}
getTask(taskId: string): Task {
const task = this.tasks.find(task => tas