Open source widget - swagger API Access Code Generator (js/typescript)

Keywords: Javascript TypeScript Front-end github axios

Nowadays, front-end and back-end separation is popular. Back-end usually uses swagger to generate api documents and provide them to front-end colleagues for invocation. Generally, front-end is to view this document and write invocation code according to the document description. In fact, swagger has provided enough descriptive information, we can directly generate relevant call code based on swagger, saving front-end time.

Open source address: swagger-2-ts

Realization principle

Opening swagger-ui, we can see that / v2/api-docs is requested to obtain API document information, in which definitions are DTO object definitions and paths are API interface lists:

Therefore, we download the api-docs and parse it to generate the corresponding call code.

There are many ways to make code generators, most of which are based on templates, and this is no exception. The difference is, this time we're going to take advantage of it. Yeoman Frame. Yeoman is a scaffolding tool for code generator. You can visit the official website to see the details.

The code generator needs users to provide some parameters, such as swagger's address, code type, etc. Yeoman provides prompting function, which can define prompts, and finally get user parameters through this.props.

  prompting() {
    // Have Yeoman greet the user.
    this.log(
      yosay(
        `Welcome to the swagger 2 typescript ${chalk.red(
          'generator-swagger-2-ts'
        )} generator!`
      )
    );

    const prompts = [
      {
        type: 'input',
        name: 'swaggerUrl',
        message: 'please input swagger url,eg:http://localhost:8051/swagger-ui.html',
        default: 'http://localhost:8051/swagger-ui.html'
      },
      {
        type: 'input',
        name: 'className',
        message: 'please enter class Name of the generated API',
        default: 'API'
      },
      {
        type: 'list',
        name: 'type',
        message: 'please choose generated API type , js or typescript',
        choices: [
          {
            name: 'typescript',
            value: 'typescript'
          },
          {
            name: 'javascript',
            value: 'js'
          }
        ]
      },
      {
        type: 'input',
        name: 'outPutFile',
        message: 'Please enter the API file name',
        default: 'api.ts'
      }
    ];

    return this.prompt(prompts).then(props => {
      this.props = props;
    });
  }

Next is code generation, which implements the writing function.

  • Download api-docs, let users provide swagger-ui address, and then calculate api-dos path
  • Parsing json
  • Yeoman's template is based on the class file generated from the template. ejs
writing() {
    let swaggerUrl = this.props.swaggerUrl.replace('swagger-ui.html', 'v2/api-docs');
    let clsName = this.props.className;
    let outPutFile = this.props.outPutFile;
    let isTypescript = this.props.type === "typescript";
    axios.get(swaggerUrl).then(response => {
      if (response.status == 200) {
        let swagger = response.data;
        var swaggerData = codegen.getViewForSwagger(
          { swagger: swagger, className: clsName },
          'typescript'
        );
        swaggerData.defaultDomain = this.props.swaggerUrl.replace('/swagger-ui.html', '');
        this.fs.copyTpl(
          this.templatePath(isTypescript ? 'ts.ejs' : 'js.ejs'),
          this.destinationPath(outPutFile),
          swaggerData
        );
      } else {
        console.error("can't fond swaager api-docs");
      }
    });

Installation and use

Need to be installed at the same time Yeoman and swagger-2-ts

npm install -g yo
npm install -g generator-swagger-2-ts

Then cd to your working directory, execute:

yo swagger-2-ts

Press prompt

  • Enter the swagger-ui address, such as http://192.168.86.8:8051/swagger-ui.html, and the package will automatically replace the url address ('swagger-ui.html','v2/api-docs') to get swagger-api-docs, then download it and parse it to generate api class.
  • Optional generation of js or typescript
  • You can customize the generated api class name, api file name
C:\Users\Administrator>yo swagger-2-ts

     _-----_     ╭──────────────────────────╮
    |       |Welcome to the swagger 2 │
    |--(o)--|typescript`---------´   │  generator-swagger-2-ts  │
    ( _´U`_ )    │        generator!        │
    /___A___\   /╰──────────────────────────╯
     |  ~  |
   __'.___.'__
 ´   `  |° ´ Y `

? please input swagger url,eg:http://localhost:8051/swagger-ui.html http://localhost:8051/swagger-ui.html
? please enter class Name of the generated API API
? please choose generated API type , js or typescript typescript
? Please enter the API file name api.ts
   create api.ts

Generate code demo:

export default class API {
    $defaultDomain = 'http://localhost:8051'
    /**
    * @method
    * @name API#getSkillsUsingGET
    * @param string authorization  
    * @param $domain 
    */
    getSkillsUsingGET (parameters){ 
      let body = null;
      let config = {
        baseURL: parameters.$domain || this.$defaultDomain,
        url: '/api/skill',
        method: 'GET'
      };
      config.headers = {}
      config.headers['Accept'] = '*/*';
      config.headers['authorization'] = parameters.authorization;
      config.data = body
      return axios.request( config );
    }
}

Using the generated API Class

var API = require("./api");
var api = new API("http://192.168.86.8:8051");
api.getSkillsUsingGET({}).then(function (response) {
    console.log(response.data);
});

Reference for reference

License

Apache-2.0 © jadepeng

Author: Jadepeng
Origin: jqpeng's technical notebook-- http://www.cnblogs.com/xiaoqi
Your support is the biggest encouragement to bloggers. Thank you for your careful reading.
Copyright of this article belongs to the author. Reproduction is welcomed, but without the consent of the author, the statement must be retained, and the link of the original text should be given clearly on the page of the article. Otherwise, the right to pursue legal responsibility should be reserved.

Posted by badapple on Sat, 15 Dec 2018 06:24:03 -0800