One, foreword
- Start to write the swagger2ts package, just don’t want to write the definition and comments of the data returned by the back end (interface-d.ts file)
- The working colleague wanted to find this definition through the interface address, so he added a Paths file (path.ts).
- The second version of the middle platform students want to make it to meet the company’s request layer solution, which is to generate directly called functions (function.ts).
Video link
Second, the analysis
In fact, if we use swagger on the interface (other tools are similar), you will find that the interface has type, has comment (see below). Go to the console, network, find /xx/api-docs, and return to definitions, Paths, etc.
- Definitions is a data dependency that generates interface. D. ts
- Paths is the data dependency that generates the paths.d.ts file and function.ts file
Three, take action
- Webpack plugin (v2.0.2) Swagger-ts-plugin
- Vscode plugin (v0.0.17) vscode-swagger2ts-plugin
Iv. Plug-in functions
Based on the user’s configuration, the following is generated in the configuration path
├ ─ ─ swagger2ts ├ ─ ─ [serviceName1] ├ ─ ─ interface, which s ├ ─ ─ paths, which s └ ─ ─ function. The ts ├ ─ ─ [serviceName2] ├ ─ ─ Interface, which s ├ ─ ─ paths, which s └ ─ ─ function. The ts ├ ─ ─ [...]. ├ ─ ─ request. Ts └ ─ ─ transation. JsonCopy the code
1. The service-xxx/ interface-.d. ts file functions
Ts definitions and TSDoc comments for all Dtos under the current service (below)
/ * * *@param AnswerContent (string) answerContent *@param AnswerPersonId (string) answerPersonId *@param SubjectInfoDTO (subjectInfoDTO) subject information */
export interface AnswerDTO {
answerContent: string | null;
answerPersonId: string | null;
subjectInfoDTO: SubjectInfoDTO;
}
Copy the code
2. The function of service-xxx/paths.d. s file
Addresses of all interfaces in the current service, and corresponding request modes and input/output parameter types (from interface.d.ts). Find the interface to jump to the definition by f12(CTRL + click)
import { AnswerDTO } from './interface.d';
interface pathsObj {
"/calendar/aaa": {
method: "post";
parameters:{
query:any;
},
data: Array<AnswerDTO>;
};
}
Copy the code
3. Function of the service-xxx/function.ts file
Receive an axiOS instance or other HTTP library wrapped around promise. Generates a unique function for each interface that knows the interface address, request mode, and input/output parameter type.
/** * Note: Get the visit appointment reminder list */
export const getSubjectVisitAppointNoticeListUsingPOST = function(this: any,params: {
query: {isAppointed: number; }; body: Partial<SubjectVisitAppointDTO>; }) :Promise<PageInfo_SubjectVisitOutputDTO> {
return this.__http.post('/service-xxx' + url, body) as any;
};
Copy the code
4. Translation. Json file function
Save the result of last translation, limit the total number of characters in third party translation.
5. Function of request.ts file
Finally, the user directly uses the file, output an API function, contains all service call interface functions
Configuration and use (choose one of three)
parameter
Name | Type | Default | Description |
---|---|---|---|
*serverList |
{Array<{serviceName: string; serviceUrl:string; } or string >} |
[] |
Mandatory If the array string [‘sms-service’] is the back-end service name, if the string object, the service name and service address must be passed |
*appUrl |
{String} |
"http://eureka.dev.com:1111/eureka/apps" |
All back-end service registration information must be uploaded |
*outputPath |
{String} |
{path.resolve(__dirname, "./src/swagger2ts")} |
Generate file output path |
fanyi |
{object} |
{baidu: { appid: "xxx",secretKey: "xxxx",maxLimit: 2000}} |
Set the appID and key. MaxLimit cannot exceed 2000 |
1. Use webPack plug-in
webpack.config.js
const Swapper2TsPlugin = require("swagger-ts-plugin");
/ * * * * appUrl outputPath output address must be the company had been all services list address http://eureka.dev.com:1111 + / had been/apps * current address returns the XML format data, the plugin will deal with * /
// I want to parse all the folders in the project, and automatically check the service name and service address, but it is not very easy to do
// So it's not really a Webpack plug-in,
module.exports = {
plugins: [
new Swapper2TsPlugin({
outputPath: path.resolve(__dirname, ".. /"),
// V1.1.11 supports this mixed type
serverList: [
"trialpartner-web"."sms-service",
{
serviceName: "xxx-service".serviceUrl: "http://172.12.12.111:8001/"],},/ / if only provide the name of the service in the serverList, http://eureka.dev.com:1111 (eureka address) must be provided on + / had been/apps
appUrl: "http://eureka.dev.com:1111/eureka/apps",})]};Copy the code
2, as a tool (lazy not to do cli ^ O ^)
// Since the swagger-ts-plugin plugin also directly exposes the build method, developers can call it directly
// NPM scripts add a name, "build:ts":"node xxx.js";
// Create a xxx.js;
new Swapper2TsPlugin({
/* configuration, as above */
}).build();
// Run yarn build:ts
Copy the code
3. Vscode plug-in (currently version 1, to be upgraded later)
-
Find vscode- Swagger2ts-Plugin in vscode market
-
To configure, go to File -> Preferences -> Settings to find swagger-ts-Plugin;
- Configure appUrl for the Eureka service list, for example, http://eureka address/Eureka /apps
- Configure the service name and service object (as follows).
// vscode plugins are configured separately, where the configuration is equivalent to serverList
"swagger-ts-plugin.serviceList": [{"serviceName": "xxx-service"."serviceUrl": "http://172.20.37.153:8000/",},"sms-service"
]
Copy the code
-
Use CTRL + Shift + P to open the Command Palette and enter Swagger2ts.
-
Please note that if a new vscode window is opened without selecting a file, no file will be generated. If your configuration is ok, the current window also selects the file project. You will get a Swagger2TS folder at the root of the file containing multiple subfolders equal to the number of configured services.
-
The vscode plugin adds an extra ignore /swagger2ts configuration to the.gitignore file in the root directory.
How will the generated data be used
Video link
// test.ts the address here is based on the generated swagger2ts file
import request from "xxx/swagger2ts/request.ts";
import axios from "axios";
let http = tmsRequest.create({
timeout: 500000.baseURL: "/api/"});const API = request(http);
// Request through the gateway
API["Service Name"] ["Back-end interface address"] ("Parameters").then((val) = > {});
/ / case
const msg = API.smsService["/homeMenu/getHomeMenuList"] ({body: {
projectId: "xxx".siteId: "xxx".subjectInfoId: "xxx",
},
}).then((val) = > {});
Copy the code
Completed function
- Enter the definition section interface.d.ts.
- Interface corresponding access parameters, request mode, etc. Paths.
- Generates a directly callable function function.ts.
- Finally, the API function request.ts is exported.
- The definition name contains a Chinese part and is translated into English using translation.
- Compatible with swagger3.0(not perfect).
- Whether adding a field to the definition is optional based on the required field
Content to be improved in the future
- Plug-in unit testing
- auto mock
- Vscode plug-in upgraded to 2.0.
- The serviceList service name is case sensitive and case insensitive
- The catch part of the returned function is not yet complete
- Configure the controller to output only the functions you want.
- Complete the unused function Tree shaking
The last
This is the first time to write an article. There are many shortcomings. If you have any suggestions, please contact me at [email protected].
⭐️⭐️ thanks ~ swagger-ts-plugin
vscode-swagger2ts-plugin