自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

JavaScript 中基于 swagger-decorator 的自動實體類構(gòu)建與 Swagger 接口文檔生成

開發(fā) 開發(fā)工具
JavaScript 中基于 swagger-decorator 的自動實體類構(gòu)建與 Swagger 接口文檔生成是筆者對于開源項目 swagger-decorator 的描述,對于不反感使用注解的項目中利用 swagger-decorator 添加合適的實體類或者接口類注解,從而實現(xiàn)支持嵌套地實體類校驗與生成、Sequelize 等 ORM 模型生成、基于 Swagger 的接口文檔生成等等功能。

JavaScript 中基于 swagger-decorator 的自動實體類構(gòu)建與 Swagger 接口文檔生成是筆者對于開源項目 swagger-decorator 的描述,對于不反感使用注解的項目中利用 swagger-decorator 添加合適的實體類或者接口類注解,從而實現(xiàn)支持嵌套地實體類校驗與生成、Sequelize 等 ORM 模型生成、基于 Swagger 的接口文檔生成等等功能。如果有對 JavaScript 語法使用尚存不明的可以參考 JavaScript 學習與實踐資料索引或者現(xiàn)代 JavaScript 開發(fā):語法基礎(chǔ)與實踐技巧系列文章。

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

swagger-decorator 的初衷是為了簡化 JavaScript 應(yīng)用開發(fā),筆者在編寫 JavaScript 應(yīng)用(Web 前端 & Node.js)時發(fā)現(xiàn)我們經(jīng)常需要重復(fù)地創(chuàng)建實體類、添加注釋或者進行類型校驗,swagger-decorator 希望能夠讓開發(fā)者一處注解、多處使用。需要強調(diào)的是,在筆者多年的 Java 應(yīng)用開發(fā)中也感受到,過多過度的注解反而會大大削弱代碼的可讀性,因此筆者也建議應(yīng)該在合適的時候舒心地使用 swagger-decorator,而不是本末倒置,一味地追求注解覆蓋率。swagger-decorator 已經(jīng)可以用于實體類生成與校驗、Sequelize ORM 實體類生成、面向 Koa 的路由注解與 Swagger 文檔自動生成。我們可以使用 yarn 或者 npm 安裝 swagger-decorator 依賴,需要注意的是,因為我們在開發(fā)中還會用到注解語法,因此還需要添加 babel-plugin-transform-decorators-legacy 插件以進行語法兼容轉(zhuǎn)化。

  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. # 導入需要的工具函數(shù) 
  13. import {  
  14.     wrappingKoaRouter, 
  15.     entityProperty, 
  16.     ... 
  17. from "swagger-decorator"

實體類注解

swagger-decorator 的核心 API 即是對于實體類的注解,該注解不會改變實體類的任何屬性表現(xiàn),只是會將注解限定的屬性特性記錄在內(nèi)置的 innerEntityObject 單例中以供后用。屬性注解 entityProperty 的方法說明如下:

  1. /** 
  2.  * Description 創(chuàng)建某個屬性的描述 
  3.  * @param type 基礎(chǔ)類型 self - 表示為自身 
  4.  * @param description 描述 
  5.  * @param required 是否為必要參數(shù) 
  6.  * @param defaultValue 默認值 
  7.  * @param pattern 
  8.  * @param primaryKey 是否為主鍵 
  9.  * @returns {Function
  10.  */ 
  11. export function entityProperty({ 
  12.   // 生成接口文檔需要的參數(shù) 
  13.   type = "string"
  14.   description = ""
  15.   required = false
  16.   defaultValue = undefined, 
  17.  
  18.   // 進行校驗所需要的參數(shù) 
  19.   pattern = undefined, 
  20.  
  21.   // 進行數(shù)據(jù)庫連接需要的參數(shù) 
  22.   primaryKey = false 
  23. }) {} 

簡單的用戶實體類注解如下,這里的數(shù)據(jù)類型 type 支持 Swagger 默認的字符格式的類型描述,也支持直接使用 JavaScript 類名或者 JavaScript 數(shù)組。

  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 內(nèi)置數(shù)據(jù)類型定義:

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 函數(shù)為實體類生成實例;不同于直接使用 new 關(guān)鍵字創(chuàng)建,instantiate 能夠根據(jù)指定屬性的數(shù)據(jù)類型或者格式進行校驗,同時能夠迭代生成嵌套地子對象。

  1. /** 
  2.  * Description 從實體類中生成對象,并且進行數(shù)據(jù)校驗;注意,這里會進行遞歸生成,即對實體類對象同樣進行生成 
  3.  * @param EntityClass 實體類 
  4.  * @param data 數(shù)據(jù)對象 
  5.  * @param ignore 是否忽略校驗 
  6.  * @param strict 是否忽略非預(yù)定義類屬性 
  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 從實體類中生成對象,并且進行數(shù)據(jù)校驗;注意,這里會進行遞歸生成,即對實體類對象同樣進行生成 
  3.  * @param EntityClass 實體類 
  4.  * @param data 數(shù)據(jù)對象 
  5.  * @param ignore 是否忽略校驗 
  6.  * @param strict 是否忽略非預(yù)定義類屬性 
  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("測試實體類實例化函數(shù)", () => { 
  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 參數(shù)可以允許忽略校驗", () => { 
  37.     instantiate( 
  38.       User
  39.       { 
  40.         name"name" 
  41.       }, 
  42.       { 
  43.         ignoretrue 
  44.       } 
  45.     ); 
  46.   }); 
  47.  
  48.   test("測試 strict 參數(shù)可以控制是否忽略額外參數(shù)", () => { 
  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 應(yīng)用中常用的 ORM 框架,swagger-decorator 提供了 generateSequelizeModel 函數(shù)以方便從實體類中利用現(xiàn)有的信息生成 Sequelize 對象模型;generateSequelizeModel 的第一個參數(shù)輸入實體類,第二個參數(shù)輸入需要覆寫的模型屬性,第三個參數(shù)設(shè)置額外屬性,譬如是否需要將駝峰命名轉(zhuǎn)化為下劃線命名等等。

  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 的靜態(tài)類型檢測工具,因此筆者添加了 flowToDecorator 函數(shù)以自動地從 Flow 聲明的類文件中提取出類型信息;內(nèi)部原理參考現(xiàn)代 JavaScript 開發(fā):語法基礎(chǔ)與實踐技巧 一書中的 JavaScript 語法樹與代碼轉(zhuǎn)化章節(jié)。該函數(shù)的使用方式為:

  1. // @flow 
  2.  
  3. import { flowToDecorator } from '../../../../src/transform/entity/flow/flow'
  4.  
  5. test('測試從 Flow 中提取出數(shù)據(jù)類型并且轉(zhuǎn)化為 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. }); 

這里對應(yīng)的 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; 

轉(zhuǎn)化后的實體類為:

  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 文檔規(guī)范可以參考 OpenAPI Specification ,而對于 swagger-decorator 的實際使用可以參考本項目的使用示例或者 基于 Koa2 的 Node.js 應(yīng)用模板 。

封裝路由對象

  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 中是負責具體的業(yè)務(wù)實現(xiàn),為了避免過多的注解文檔對于代碼可讀性的干擾,筆者建議是將除了路徑與描述之外的信息放置到父類中聲明;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 {} 

運行應(yīng)用

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

  1. /swagger/api.json 

 【本文是51CTO專欄作者“張梓雄 ”的原創(chuàng)文章,如需轉(zhuǎn)載請通過51CTO與作者聯(lián)系】

戳這里,看該作者更多好文

責任編輯:武曉燕 來源: 51CTO專欄
相關(guān)推薦

2017-06-20 15:39:58

Koa2 應(yīng)用動態(tài)Swagger文檔

2023-03-08 08:48:50

Swag工具

2023-03-06 08:53:13

2023-09-21 10:44:41

Web服務(wù)Swagger前端

2024-09-10 08:15:33

Asp項目API

2023-08-09 08:37:44

2020-12-07 06:05:34

apidocyapiknife4j

2022-02-16 08:21:11

JavaSwagger工具

2022-09-06 09:00:07

后端分離項目

2017-08-10 16:14:07

FeignRPC模式

2009-09-10 10:09:46

LINQ to SQL

2020-08-06 11:45:37

數(shù)據(jù)庫文檔Swagger

2022-07-28 10:39:50

OpenApiSwaggerSpringDoc

2024-05-16 08:28:20

類型處理器D3BootJSON

2021-05-07 20:27:14

SpringBootSwagger3文檔

2022-01-28 14:39:59

Swaggerpostmanmock

2020-04-22 10:35:57

實體類屬性映射

2018-11-19 14:48:10

SwaggerString函數(shù)

2022-09-08 09:05:15

Swagger接口工具

2022-07-21 11:04:53

Swagger3Spring
點贊
收藏

51CTO技術(shù)棧公眾號