0%

用 typescript 生成 Swagger 文档

用 typescript 生成 Swagger 文档

参考地址:https://wz2cool.github.io/2018/04/14/swagger-ts-doc-start/

apiModelProperty 装饰器

这个装饰器主要是为了生成 definitions 中的 model,我们看代码可看到如何描述一个 typescript 中的一个类。

1
2
3
4
5
6
7
8
9
10
11
12
import { apiModelProperty, DataType } from "swagger-ts-doc";

export class UpdateStudentDto {
@apiModelProperty(
DataType.STRING, // 类型
false, // 是否必填
"学生姓名" // 描述
)
public name: string;
@apiModelProperty(DataType.INTEGER, false, "学生年龄")
public age: number;
}

最后会生成与之对应的 swagger json 描述(这里我们不使用 yaml 语法,使用的 json 语法)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
"UpdateStudentDto": {
"type": "object",
"required": ["name", "age"],
"properties": {
"name": {
"type": "string",
"description": "学生姓名"
},
"age": {
"type": "integer",
"description": "学生年龄"
}
}
},

Request 参数

参考 swagger 文档:
https://swagger.io/docs/specification/describing-parameters/
https://swagger.io/docs/specification/describing-request-body/

  • RequestBody 类对应文档 requestBody
  • PathVariable 类对应文档 path parameters (in: path)
  • RequestParam 类对弈文档 query parameters (in: query)

Reponse

参考 swagger 文档:
https://swagger.io/docs/specification/describing-responses/
我们看一下定义多个返回相应

1
2
3
4
5
[
new Response(HttpStatusCode.OK, DataType.STRING, "ok"),
new Response(HttpStatusCode.INTERNAL_SERVER_ERROR, DataType.STRING, "内部错误"),
new Response(HttpStatusCode.NOT_FOUND, DataType.STRING, "学生未找到"),
],

registerRequestMapping 方法

这里就是我们要去生成 swagger 中 paths 节点调用的方法,这里我们举一个修改学生的一个例子。

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
29
30
31
32
33
34
35
36
 registerRequestMapping(
StudentApi, // tags 类似于把一些路由放到一个组里面
"/students/{id}", // 路由
RequestMethod.PUT,
[
new PathVariable("id", DataType.STRING, "学生ID"),
new RequestBody("student", DataType.OBJECT, UpdateStudentDto, "学生"),
],
[
new Response(HttpStatusCode.OK, DataType.STRING, "ok"),
new Response(HttpStatusCode.INTERNAL_SERVER_ERROR, DataType.STRING, "内部错误"),
new Response(HttpStatusCode.NOT_FOUND, DataType.STRING, "学生未找到"),
],
"修改学生"); // 对这个路由的描述
route.put("/:id", (req, res, next) => {
const input = req.body;
const id = req.params.id;
if (!id) {
res.status(HttpStatusCode.INTERNAL_SERVER_ERROR);
res.json("学生ID不能为空");
return;
}

if (lodash.findIndex(this.students, (x) => x.uuid === id) < 0) {
res.status(HttpStatusCode.NOT_FOUND);
res.json(`未能找到学生`);
return;
}

const student = new Student();
student.uuid = id;
student.name = input.name;
student.age = input.age;
this.modifyStudent(student);
res.json("ok");
});

本文作者:草梅友仁
本文地址: https://blog.cmyr.ltd/archives/bbc1fd72.html
版权声明:转载请注明出处!

坚持原创技术分享,您的支持将鼓励我继续创作!