JavaScript 中基于 swagger-decorator 的自动实体类构建与 Swagger 接口文档生成

开发 开发工具
JavaScript 中基于 swagger-decorator 的自动实体类构建与 Swagger 接口文档生成是笔者对于开源项目 swagger-decorator 的描述,对于不反感使用注解的项目中利用 swagger-decorator 添加合适的实体类或者接口类注解,从而实现支持嵌套地实体类校验与生成、Sequelize 等 ORM 模型生成、基于 Swagger 的接口文档生成等等功能。

JavaScript 中基于 swagger-decorator 的自动实体类构建与 Swagger 接口文档生成是笔者对于开源项目 swagger-decorator 的描述,对于不反感使用注解的项目中利用 swagger-decorator 添加合适的实体类或者接口类注解,从而实现支持嵌套地实体类校验与生成、Sequelize 等 ORM 模型生成、基于 Swagger 的接口文档生成等等功能。如果有对 JavaScript 语法使用尚存不明的可以参考 JavaScript 学习与实践资料索引或者现代 JavaScript 开发:语法基础与实践技巧系列文章

swagger-decorator: 一处注解,多处使用

swagger-decorator 的初衷是为了简化 JavaScript 应用开发,笔者在编写 JavaScript 应用(Web 前端 & Node.js)时发现我们经常需要重复地创建实体类、添加注释或者进行类型校验,swagger-decorator 希望能够让开发者一处注解、多处使用。需要强调的是,在笔者多年的 Java 应用开发中也感受到,过多过度的注解反而会大大削弱代码的可读性,因此笔者也建议应该在合适的时候舒心地使用 swagger-decorator,而不是本末倒置,一味地追求注解覆盖率。swagger-decorator 已经可以用于实体类生成与校验、Sequelize ORM 实体类生成、面向 Koa 的路由注解与 Swagger 文档自动生成。我们可以使用 yarn 或者 npm 安装 swagger-decorator 依赖,需要注意的是,因为我们在开发中还会用到注解语法,因此还需要添加 babel-plugin-transform-decorators-legacy 插件以进行语法兼容转化。

  1. # 使用 npm 安装依赖 
  2.  
  3. $ npm install swagger-decorator -S 
  4.  
  5.  
  6. # 使用 yarn 安装依赖 
  7.  
  8. $ yarn add swagger-decorator 
  9.  
  10. $ yarn add babel-plugin-transform-decorators-legacy -D 
  11.  
  12. # 导入需要的工具函数 
  13. import {  
  14.     wrappingKoaRouter, 
  15.     entityProperty, 
  16.     ... 
  17. from "swagger-decorator"

实体类注解

swagger-decorator 的核心 API 即是对于实体类的注解,该注解不会改变实体类的任何属性表现,只是会将注解限定的属性特性记录在内置的 innerEntityObject 单例中以供后用。属性注解 entityProperty 的方法说明如下:

  1. /** 
  2.  * Description 创建某个属性的描述 
  3.  * @param type 基础类型 self - 表示为自身 
  4.  * @param description 描述 
  5.  * @param required 是否为必要参数 
  6.  * @param defaultValue 默认值 
  7.  * @param pattern 
  8.  * @param primaryKey 是否为主键 
  9.  * @returns {Function
  10.  */ 
  11. export function entityProperty({ 
  12.   // 生成接口文档需要的参数 
  13.   type = "string"
  14.   description = ""
  15.   required = false
  16.   defaultValue = undefined, 
  17.  
  18.   // 进行校验所需要的参数 
  19.   pattern = undefined, 
  20.  
  21.   // 进行数据库连接需要的参数 
  22.   primaryKey = false 
  23. }) {} 

简单的用户实体类注解如下,这里的数据类型 type 支持 Swagger 默认的字符格式的类型描述,也支持直接使用 JavaScript 类名或者 JavaScript 数组。

  1. // @flow 
  2.  
  3. import { entityProperty } from "../../src/entity/decorator"
  4. import UserProperty from "./UserProperty"
  5. /** 
  6.  * Description 用户实体类 
  7.  */ 
  8. export default class User { 
  9.   // 编号 
  10.   @entityProperty({ 
  11.     type: "integer"
  12.     description: "user id, auto-generated"
  13.     required: true 
  14.   }) 
  15.   id: string = 0; 
  16.  
  17.   // 姓名 
  18.   @entityProperty({ 
  19.     type: "string"
  20.     description: "user name, 3~12 characters"
  21.     required: false 
  22.   }) 
  23.   name: string = "name"
  24.  
  25.   // 邮箱 
  26.   @entityProperty({ 
  27.     type: "string"
  28.     description: "user email"
  29.     pattern: "email"
  30.     required: false 
  31.   }) 
  32.   email: string = "email"
  33.  
  34.   // 属性 
  35.   @entityProperty({ 
  36.     type: UserProperty, 
  37.     description: "user property"
  38.     required: false 
  39.   }) 
  40.   property: UserProperty = new UserProperty(); 
  41.  
  42. export default class UserProperty { 
  43.   // 朋友列表 
  44.   @entityProperty({ 
  45.     type: ["number"], 
  46.     description: "user friends, which is user ids"
  47.     required: false 
  48.   }) 
  49.   friends: [number]; 

Swagger 内置数据类型定义:

Common NametypeformatCommentsintegerintegerint32signed 32 bitslongintegerint64signed 64 bitsfloatnumberfloatdoublenumberdoublestringstringbytestringbytebase64 encoded charactersbinarystringbinaryany sequence of octetsbooleanbooleandatestringdateAs defined by full-date - RFC3339dateTimestringdate-timeAs defined by date-time - RFC3339passwordstringpasswordUsed to hint UIs the input needs to be obscured.

实例生成与校验

实体类定义完毕之后,我们首先可以使用 instantiate 函数为实体类生成实例;不同于直接使用 new 关键字创建,instantiate 能够根据指定属性的数据类型或者格式进行校验,同时能够迭代生成嵌套地子对象。

  1. /** 
  2.  * Description 从实体类中生成对象,并且进行数据校验;注意,这里会进行递归生成,即对实体类对象同样进行生成 
  3.  * @param EntityClass 实体类 
  4.  * @param data 数据对象 
  5.  * @param ignore 是否忽略校验 
  6.  * @param strict 是否忽略非预定义类属性 
  7.  * @throws 当校验失败,会抛出异常 
  8.  */ 
  9. export function instantiate( 
  10.   EntityClass: Function
  11.   data: { 
  12.     [string]: any 
  13.   }, 
  14.   { ignore = false, strict = true }: { ignore: boolean, strict: boolean } = {} 
  15. ): Object {} 

这里为了方便描述使用 Jest 测试用例说明不同的使用场景:

  1. /** 
  2.  * Description 从实体类中生成对象,并且进行数据校验;注意,这里会进行递归生成,即对实体类对象同样进行生成 
  3.  * @param EntityClass 实体类 
  4.  * @param data 数据对象 
  5.  * @param ignore 是否忽略校验 
  6.  * @param strict 是否忽略非预定义类属性 
  7.  * @throws 当校验失败,会抛出异常 
  8.  */ 
  9. export function instantiate( 
  10.   EntityClass: Function
  11.   data: { 
  12.     [string]: any 
  13.   }, 
  14.   { ignore = false, strict = true }: { ignore: boolean, strict: boolean } = {} 
  15. ): Object {} 
  16. 这里为了方便描述使用 Jest 测试用例说明不同的使用场景: 
  17.  
  18. describe("测试实体类实例化函数", () => { 
  19.   test("测试 User 类实例化校验", () => { 
  20.     expect(() => { 
  21.       instantiate(User, { 
  22.         name"name" 
  23.       }).toThrowError(/validate fail!/); 
  24.     }); 
  25.  
  26.     let user = instantiate(User, { 
  27.       id: 0, 
  28.       name"name"
  29.       email: "a@q.com" 
  30.     }); 
  31.  
  32.     // 判断是否为 User 实例 
  33.     expect(user).toBeInstanceOf(User); 
  34.   }); 
  35.  
  36.   test("测试 ignore 参数可以允许忽略校验", () => { 
  37.     instantiate( 
  38.       User
  39.       { 
  40.         name"name" 
  41.       }, 
  42.       { 
  43.         ignoretrue 
  44.       } 
  45.     ); 
  46.   }); 
  47.  
  48.   test("测试 strict 参数可以控制是否忽略额外参数", () => { 
  49.     let user = instantiate( 
  50.       User
  51.       { 
  52.         name"name"
  53.         external: "external" 
  54.       }, 
  55.       { 
  56.         ignoretrue
  57.         strict: true 
  58.       } 
  59.     ); 
  60.  
  61.     expect(user).not.toHaveProperty("external""external"); 
  62.  
  63.     user = instantiate( 
  64.       User
  65.       { 
  66.         name"name"
  67.         external: "external" 
  68.       }, 
  69.       { 
  70.         ignoretrue
  71.         strict: false 
  72.       } 
  73.     ); 
  74.  
  75.     expect(user).toHaveProperty("external""external"); 
  76.   }); 
  77. }); 
  78.  
  79. describe("测试嵌套实例生成", () => { 
  80.   test("测试可以递归生成嵌套实体类", () => { 
  81.     let user = instantiate(User, { 
  82.       id: 0, 
  83.       property: { 
  84.         friends: [0] 
  85.       } 
  86.     }); 
  87.  
  88.     expect(user.property).toBeInstanceOf(UserProperty); 
  89.   }); 
  90. }); 

Sequelize 模型生成

Sequelize 是 Node.js 应用中常用的 ORM 框架,swagger-decorator 提供了 generateSequelizeModel 函数以方便从实体类中利用现有的信息生成 Sequelize 对象模型;generateSequelizeModel 的第一个参数输入实体类,第二个参数输入需要覆写的模型属性,第三个参数设置额外属性,譬如是否需要将驼峰命名转化为下划线命名等等。

  1. const originUserSequelizeModel = generateSequelizeModel( 
  2.   User
  3.   { 
  4.     _id: { 
  5.       primaryKey: true 
  6.     } 
  7.   }, 
  8.   { 
  9.     mappingCamelCaseToUnderScore: true 
  10.   } 
  11. ); 
  12.  
  13. const UserSequelizeModel = sequelize.define( 
  14.   "b_user"
  15.   originUserSequelizeModel, 
  16.   { 
  17.     timestamps: false
  18.     underscored: true
  19.     freezeTableName: true 
  20.   } 
  21. ); 
  22.  
  23. UserSequelizeModel.findAll({ 
  24.   attributes: { exclude: [] } 
  25. }).then(users => { 
  26.   console.log(users); 
  27. }); 

从 Flow 类型声明中自动生成注解

笔者习惯使用 Flow 作为 JavaScript 的静态类型检测工具,因此笔者添加了 flowToDecorator 函数以自动地从 Flow 声明的类文件中提取出类型信息;内部原理参考现代 JavaScript 开发:语法基础与实践技巧 一书中的 JavaScript 语法树与代码转化章节。该函数的使用方式为:

  1. // @flow 
  2.  
  3. import { flowToDecorator } from '../../../../src/transform/entity/flow/flow'
  4.  
  5. test('测试从 Flow 中提取出数据类型并且转化为 Swagger 接口类', () => { 
  6.   flowToDecorator('./TestEntity.js''./TestEntity.transformed.js').then
  7.     codeStr => { 
  8.       console.log(codeStr); 
  9.     }, 
  10.     err => { 
  11.       console.error(err); 
  12.     } 
  13.   ); 
  14. }); 

这里对应的 TestEntity 为:

  1. // @flow 
  2.  
  3. import AnotherEntity from "./AnotherEntity"
  4.  
  5. class Entity { 
  6.   // Comment 
  7.   stringProperty: string = 0; 
  8.  
  9.   classProperty: Entity = null
  10.  
  11.   rawProperty; 
  12.  
  13.   @entityProperty({ 
  14.     type: "string"
  15.     description: "this is property description"
  16.     required: true 
  17.   }) 
  18.   decoratedProperty; 

转化后的实体类为:

  1. // @flow 
  2.  
  3. import { entityProperty } from 'swagger-decorator'
  4.  
  5. import AnotherEntity from './AnotherEntity'
  6.  
  7. class Entity { 
  8.   // Comment 
  9.   @entityProperty({ 
  10.     type: 'string'
  11.     required: false
  12.     description: 'Comment' 
  13.   }) 
  14.   stringProperty: string = 0; 
  15.  
  16.   @entityProperty({ 
  17.     type: Entity, 
  18.     required: false 
  19.   }) 
  20.   classProperty: Entity = null
  21.  
  22.   @entityProperty({ 
  23.     type: 'string'
  24.     required: false 
  25.   }) 
  26.   rawProperty; 
  27.  
  28.   @entityProperty({ 
  29.     type: 'string'
  30.     description: 'this is property description'
  31.     required: true 
  32.   }) 
  33.   decoratedProperty; 

接口注解与 Swagger 文档生成

对于 Swagger 文档规范可以参考 OpenAPI Specification ,而对于 swagger-decorator 的实际使用可以参考本项目的使用示例或者 基于 Koa2 的 Node.js 应用模板

封装路由对象

  1. import { wrappingKoaRouter } from "swagger-decorator"
  2.  
  3. ... 
  4.  
  5. const Router = require("koa-router"); 
  6.  
  7. const router = new Router(); 
  8.  
  9. wrappingKoaRouter(router, "localhost:8080""/api", { 
  10.   title: "Node Server Boilerplate"
  11.   version: "0.0.1"
  12.   description: "Koa2, koa-router,Webpack" 
  13. }); 
  14.  
  15. // define default route 
  16. router.get("/", async function(ctx, next) { 
  17.   ctx.body = { msg: "Node Server Boilerplate" }; 
  18. }); 
  19.  
  20. // use scan to auto add method in class 
  21. router.scan(UserController); 

定义接口类

  1. export default class UserController extends UserControllerDoc { 
  2.   @apiRequestMapping("get""/users"
  3.   @apiDescription("get all users list"
  4.   static async getUsers(ctx, next): [User] { 
  5.     ctx.body = [new User()]; 
  6.   } 
  7.  
  8.   @apiRequestMapping("get""/user/:id"
  9.   @apiDescription("get user object by id, only access self or friends"
  10.   static async getUserByID(ctx, next): User { 
  11.     ctx.body = new User(); 
  12.   } 
  13.  
  14.   @apiRequestMapping("post""/user"
  15.   @apiDescription("create new user"
  16.   static async postUser(): number { 
  17.     ctx.body = { 
  18.       statusCode: 200 
  19.     }; 
  20.   } 

在 UserController 中是负责具体的业务实现,为了避免过多的注解文档对于代码可读性的干扰,笔者建议是将除了路径与描述之外的信息放置到父类中声明;swagger-decorator 会自动从某个接口类的直接父类中提取出同名方法的描述文档。

  1. export default class UserControllerDoc { 
  2.   @apiResponse(200, "get users successfully", [User]) 
  3.   static async getUsers(ctx, next): [User] {} 
  4.  
  5.   @pathParameter({ 
  6.     name"id"
  7.     description: "user id"
  8.     type: "integer"
  9.     defaultValue: 1 
  10.   }) 
  11.   @queryParameter({ 
  12.     name"tags"
  13.     description: "user tags, for filtering users"
  14.     required: false
  15.     type: "array"
  16.     items: ["string"
  17.   }) 
  18.   @apiResponse(200, "get user successfully"User
  19.   static async getUserByID(ctx, next): User {} 
  20.  
  21.   @bodyParameter({ 
  22.     name"user"
  23.     description: "the new user object, must include user name"
  24.     required: true
  25.     schemaUser 
  26.   }) 
  27.   @apiResponse(200, "create new user successfully", { 
  28.     statusCode: 200 
  29.   }) 
  30.   static async postUser(): number {} 

运行应用

  1. run your application and open swagger docs (PS. swagger-decorator contains Swagger UI): 
  2. /swagger 

  1. /swagger/api.json 

 【本文是51CTO专栏作者“张梓雄 ”的原创文章,如需转载请通过51CTO与作者联系】

戳这里,看该作者更多好文

责任编辑:武晓燕 来源: 51CTO专栏
相关推荐

2017-06-20 15:39:58

Koa2 应用动态Swagger文档

2023-03-08 08:48:50

Swag工具

2023-03-06 08:53:13

2023-09-21 10:44:41

Web服务Swagger前端

2023-08-09 08:37:44

2020-12-07 06:05:34

apidocyapiknife4j

2022-09-06 09:00:07

后端分离项目

2022-02-16 08:21:11

JavaSwagger工具

2017-08-10 16:14:07

FeignRPC模式

2009-09-10 10:09:46

LINQ to SQL

2020-08-06 11:45:37

数据库文档Swagger

2022-07-28 10:39:50

OpenApiSwaggerSpringDoc

2020-04-22 10:35:57

实体类属性映射

2022-01-28 14:39:59

Swaggerpostmanmock

2021-05-07 20:27:14

SpringBootSwagger3文档

2022-09-08 09:05:15

Swagger接口工具

2018-11-19 14:48:10

SwaggerString函数

2011-06-01 15:45:28

实体类序列化

2023-01-04 08:53:52

JPA实体类注解

2021-03-22 08:02:16

WordKnife4jSwagger
点赞
收藏

51CTO技术栈公众号