Read the swagger interface document and automatically generate front-end ts or js code

One-click generation of typescript or javascript code according to swagger (openapi) documentation

Usually when docking with the backend, it is always necessary to re-implement the type declared by the backend swagger in ts and write a bunch of interfaces; today I recommend a library that can directly generate ts or js code according to the swagger document, and has good code hints

Note: swagger document version requires 3.0 and above

First on the renderings

swagger-documentation
insert image description here

generated code

1. Install scaffolding


npm i -g @zeronejs/cli

2. Open your project

I quickly create here


npm ini -y

then create a swagger.config.jsonfile

Configuration example:


{
   "docsUrl": "http://www.example.com/v3/api-docs",
   "axiosInstanceUrl": "axios"
}

example

Where docsUrl refers to the json link address on the swagger page

swagger-documentation

json address

Of course you can also specify a local json file

example

3. Run command

3.1 ts code


zerone api

3.2 js code

Generating js depends on axios, please install axios first


npm install axios

zerone api -js

image

Code generated! execution succeed! !

4. Actual operation

Usually our project is not in the root directory, slightly modified...

We put swagger.config.jsonand docs.jsonunder /src/api, if you need to create an axios instance, axiosInstanceUrlreplace it with the address of the instance

image

4.1 Run command

ts code


zerone api -p ./src/api

js code


zerone api -js -p ./src/api

image

Generated successfully!

Since the corresponding declare file is automatically generated, even js will have good code hints

image

Complete demo code: https://gitee.com/zzh948498/swagger-to-ts

Official document address: zeronejs (ps: the document is currently mounted on github)

Source address: https://github.com/zeronejs/zerone

Guess you like

Origin blog.csdn.net/weixin_44241402/article/details/128964496