根據swagger的json數據生成js可直接使用的API文件

swagger2js

根據swagger的json數據生成js可直接使用的API文件javascript

  • 解決在實際項目中url隨處寫的問題

Installation

  • Using npm: npm install swagger2js --save
  • Using Yarn: yarn add swagger2js

Future

  • [X] 增長配置可選擇是否使用axios
  • [X] 增長變動日誌

Example

const {swagger2js} = require('../index');

swagger2js({
  swaggerUrl: 'http://your-hostname/v1/api-docs',
  pathName: __dirname + '/API'
}, {
  useAxios: true,
  useLog: true,
  saveOriginJson: true
});
複製代碼

生成的代碼java

import Axios, {
  AxiosPromise,
  AxiosRequestConfig
} from "axios";

interface Result {
  success: boolean;
  data: any;
  code: number;
  message: string;
}

/** * manage服務 * 接口文檔 * 接口數量:69 */
export default {
  _baseURL: 'http://your-hostname/pro-name/',
    _instance: null,
  
    get getInstance() {
      if (!this._instance) {
        this._instance = Axios.create({
          baseURL: this._baseURL
        })
      }
      return this._instance;
    },
  
    set baseURL(url) {
      if (this._instance) {
        throw new Error('Axios已實例化,無效操做');
      }
      this._baseURL = url;
    },
  
    getQueryParams(query) {
      let queryParams = '';
      if (query) {
        queryParams = Object.keys(query).map(key => `${key}=${query[key]}`).join('&')
      }
      return queryParams ? '?' + queryParams : '';
    },

  /** * get * @method */
    get_v1_contact_query({
      path,
      query = {},
      body = {},
      config = {}
    }: {
      path ? : {},
      query ? : {},
      body ? : {},
      config ? : AxiosRequestConfig
    } | any = {}): AxiosPromise < Result > {
  
      const requestParams = {
        url: `v1/contact/query` + this.getQueryParams(query),
        method: 'get',
        data: body,
        ...config
      };
  
      return this.getInstance.request(requestParams);
    },
}

複製代碼

Config

參數 默認值
useAxios true
useLog true
saveOriginJson true

Reference

github [github.com/yoonzm/swag…]ios

相關文章
相關標籤/搜索