zoukankan      html  css  js  c++  java
  • 【前端开发】swagger接口导出到项目中使用的解决方案

    在package.json中增加依赖

    yarn add  swagger-axios-codegen

     "swagger-axios-codegen": "^0.12.5",

    增加运行指令

     "genApi": "node src/generatorApi/index.js"

    增加如下目录(用来配置后生成api文件)

     config.js

    const host = 'http://10.14.2.27'
    const host169 = 'http://10.14.2.169'
    const modular = [
      // { name: 'op', url: '', label: '审批服务', port: 19200 },
      // { name: 'doc', url: '', label: '公文服务', port: 19210 },
      // { name: 'office', url: '', label: '行政模块', port: 19220 },
      // { name: 'meeting', url: '', label: '会议模块', port: 19230 },
      // { name: 'process', url: '', label: '事务模块', port: 19240 },
      // { name: 'supervise', url: '', label: '督办模块', port: 19260 },
      // { name: 'tz', url: '', label: '台账模块', port: 19261 },
      // { name: 'home', url: '', label: 'home模块', port: 19290 },
      // { name: 'user', url: '', label: '用户模块', port: 19110 },
      // { name: 'todo', url: '', label: 'todo模块', port: 19150 },
      // { name: 'file', url: '', label: '文件模块', port: 19140,serve:169 },
      { name: 'search', url: '', label: '检索模块', port: 19180, serve: 169 }
      // { name: 'user1', url: '', label: '用户模块', port: 19110 },
      // { name: 'file', url: '', label: '文件模块', port: 19140 },
      // { name: 'sso', url: '', label: '登录模块', port: 19100 },
    ]
    modular.forEach(item => {
      item.url = `${host}:${item.port}/v2/api-docs`
      if (item.serve === 169) {
        item.url = `${host169}:${item.port}/v2/api-docs`
      }
      // item.url = `${host}:${item.port}/v3/api-docs`
    })
    module.exports = {
      modular
    }

    index.js

    /* eslint-disable */
    // const fs = require('fs')
    const path = require('path')
    const { modular } = require('./config.js')
    const { codegen } = require('swagger-axios-codegen')
    modular.forEach((item) => {
      codegen({
        remoteUrl: item.url,
        outputDir: path.resolve(__dirname, `autoApi`),
        fileName: item.name + '.ts',
      }).catch((err) => {
        console.log(err)
      })
    })  

    依赖装好、配置改好就可以运行生成api文件了

    yarn genApi

    最终就会生成

     如search.js

    /** Generate by swagger-axios-codegen */
    // @ts-nocheck
    /* eslint-disable */
    
    /** Generate by swagger-axios-codegen */
    /* eslint-disable */
    // @ts-nocheck
    import axiosStatic, { AxiosInstance, AxiosRequestConfig } from 'axios';
      import { request } from '@/utils/request'
    
    export interface IRequestOptions extends AxiosRequestConfig {}
    
    export interface IRequestConfig {
      method?: any;
      headers?: any;
      url?: any;
      data?: any;
      params?: any;
    }
    
    // Add options interface
    export interface ServiceOptions {
      axios?: AxiosInstance;
    }
    
    // Add default options
    export const serviceOptions: ServiceOptions = {
       axios: request
    };
    
    // Instance selector
    export function axios(configs: IRequestConfig, resolve: (p: any) => void, reject: (p: any) => void): Promise<any> {
      if (serviceOptions.axios) {
        return serviceOptions.axios
          .request(configs)
          .then(res => {
            resolve(res.data);
          })
          .catch(err => {
            reject(err);
          });
      } else {
        throw new Error('please inject yourself instance like axios  ');
      }
    }
    
    export function getConfigs(method: string, contentType: string, url: string, options: any): IRequestConfig {
      const configs: IRequestConfig = { ...options, method, url };
      configs.headers = {
        ...options.headers,
        'Content-Type': contentType
      };
      return configs;
    }
    
    export const basePath = '';
    
    export interface IList<T> extends Array<T> {}
    export interface List<T> extends Array<T> {}
    export interface IDictionary<TValue> {
      [key: string]: TValue;
    }
    export interface Dictionary<TValue> extends IDictionary<TValue> {}
    
    export interface IListResult<T> {
      items?: T[];
    }
    
    export class ListResultDto<T> implements IListResult<T> {
      items?: T[];
    }
    
    export interface IPagedResult<T> extends IListResult<T> {
      totalCount?: number;
      items?: T[];
    }
    
    export class PagedResultDto<T = any> implements IPagedResult<T> {
      totalCount?: number;
      items?: T[];
    }
    
    // customer definition
    // empty
    
    export class FullTextSearchControllerService {
      /**
       * 按业务模块全文检索
       */
      static searchUsingPost1(
        params: {
          /** param */
          param: SearchParamDto;
        } = {} as any,
        options: IRequestOptions = {}
      ): Promise<SearchResultDTO> {
        return new Promise((resolve, reject) => {
          let url = basePath + '/search';
    
          const configs: IRequestConfig = getConfigs('post', 'application/json', url, options);
    
          let data = params['param'];
    
          configs.data = data;
          axios(configs, resolve, reject);
        });
      }
      /**
       * 按业务模块全文检索,按模块名统计命中文档数
       */
      static searchWithSummaryUsingPost(
        params: {
          /** param */
          param: SearchParamDto;
        } = {} as any,
        options: IRequestOptions = {}
      ): Promise<SearchResultDTO> {
        return new Promise((resolve, reject) => {
          let url = basePath + '/search/aggregations';
    
          const configs: IRequestConfig = getConfigs('post', 'application/json', url, options);
    
          let data = params['param'];
    
          configs.data = data;
          axios(configs, resolve, reject);
        });
      }
    }
    
    export class IndexManagerControllerService {
      /**
       * 获取所有索引信息
       */
      static getIndexListUsingGet(
        params: {
          /** index */
          index?: string;
        } = {} as any,
        options: IRequestOptions = {}
      ): Promise<索引总览信息> {
        return new Promise((resolve, reject) => {
          let url = basePath + '/search/admin/index';
    
          const configs: IRequestConfig = getConfigs('get', 'application/json', url, options);
          configs.params = { index: params['index'] };
          let data = null;
    
          configs.data = data;
          axios(configs, resolve, reject);
        });
      }
      /**
       * 增加索引
       */
      static addIndexUsingPost(
        params: {
          /** index */
          index?: string;
        } = {} as any,
        options: IRequestOptions = {}
      ): Promise<any> {
        return new Promise((resolve, reject) => {
          let url = basePath + '/search/admin/index';
    
          const configs: IRequestConfig = getConfigs('post', 'application/json', url, options);
          configs.params = { index: params['index'] };
          let data = null;
    
          configs.data = data;
          axios(configs, resolve, reject);
        });
      }
      /**
       * 清空索引
       */
      static clearIndexUsingPut(
        params: {
          /** index */
          index?: string;
        } = {} as any,
        options: IRequestOptions = {}
      ): Promise<any> {
        return new Promise((resolve, reject) => {
          let url = basePath + '/search/admin/index';
    
          const configs: IRequestConfig = getConfigs('put', 'application/json', url, options);
          configs.params = { index: params['index'] };
          let data = null;
    
          configs.data = data;
          axios(configs, resolve, reject);
        });
      }
      /**
       * 删除索引
       */
      static deleteIndexUsingDelete(
        params: {
          /** index */
          index?: string;
        } = {} as any,
        options: IRequestOptions = {}
      ): Promise<any> {
        return new Promise((resolve, reject) => {
          let url = basePath + '/search/admin/index';
    
          const configs: IRequestConfig = getConfigs('delete', 'application/json', url, options);
          configs.params = { index: params['index'] };
          let data = null;
    
          configs.data = data;
          axios(configs, resolve, reject);
        });
      }
      /**
       * 获取数据日志
       */
      static getDataLogUsingPost(
        params: {
          /** searchParamDto */
          searchParamDto: SearchParamDto;
        } = {} as any,
        options: IRequestOptions = {}
      ): Promise<SearchResultDTO_SearchLogResultDTO> {
        return new Promise((resolve, reject) => {
          let url = basePath + '/search/admin/index/log';
    
          const configs: IRequestConfig = getConfigs('post', 'application/json', url, options);
    
          let data = params['searchParamDto'];
    
          configs.data = data;
          axios(configs, resolve, reject);
        });
      }
      /**
       * 获取服务器信息
       */
      static getServerInfoUsingGet(options: IRequestOptions = {}): Promise<TransportAddress[]> {
        return new Promise((resolve, reject) => {
          let url = basePath + '/search/admin/index/server';
    
          const configs: IRequestConfig = getConfigs('get', 'application/json', url, options);
    
          let data = null;
    
          configs.data = data;
          axios(configs, resolve, reject);
        });
      }
    }
    
    export class CustomizeSearchControllerService {
      /**
       * 自动完成
       */
      static completionUsingGet(
        params: {
          /** autoCompleteDto */
          autoCompleteDto: AutoCompleteDto;
        } = {} as any,
        options: IRequestOptions = {}
      ): Promise<string[]> {
        return new Promise((resolve, reject) => {
          let url = basePath + '/search/customize/completion';
    
          const configs: IRequestConfig = getConfigs('get', 'application/json', url, options);
    
          let data = params['autoCompleteDto'];
    
          configs.data = data;
          axios(configs, resolve, reject);
        });
      }
      /**
       * 自动完成
       */
      static completionUsingPost(
        params: {
          /** autoCompleteDto */
          autoCompleteDto: AutoCompleteDto;
        } = {} as any,
        options: IRequestOptions = {}
      ): Promise<string[]> {
        return new Promise((resolve, reject) => {
          let url = basePath + '/search/customize/completion';
    
          const configs: IRequestConfig = getConfigs('post', 'application/json', url, options);
    
          let data = params['autoCompleteDto'];
    
          configs.data = data;
          axios(configs, resolve, reject);
        });
      }
      /**
       * 自定义数据索引
       */
      static definedIndexUsingGet(
        params: {
          /** param */
          param: JsonDataSourceDto;
        } = {} as any,
        options: IRequestOptions = {}
      ): Promise<any> {
        return new Promise((resolve, reject) => {
          let url = basePath + '/search/customize/definedIndex';
    
          const configs: IRequestConfig = getConfigs('get', 'application/json', url, options);
    
          let data = params['param'];
    
          configs.data = data;
          axios(configs, resolve, reject);
        });
      }
      /**
       * 自定义数据索引
       */
      static definedIndexUsingPost(
        params: {
          /** param */
          param: JsonDataSourceDto;
        } = {} as any,
        options: IRequestOptions = {}
      ): Promise<any> {
        return new Promise((resolve, reject) => {
          let url = basePath + '/search/customize/definedIndex';
    
          const configs: IRequestConfig = getConfigs('post', 'application/json', url, options);
    
          let data = params['param'];
    
          configs.data = data;
          axios(configs, resolve, reject);
        });
      }
      /**
       * 检索
       */
      static searchUsingPost(
        params: {
          /** param */
          param: SearchParamDto;
        } = {} as any,
        options: IRequestOptions = {}
      ): Promise<SearchResultDTO> {
        return new Promise((resolve, reject) => {
          let url = basePath + '/search/customize/search';
    
          const configs: IRequestConfig = getConfigs('post', 'application/json', url, options);
    
          let data = params['param'];
    
          configs.data = data;
          axios(configs, resolve, reject);
        });
      }
    }
    
    export class IkDictionaryControllerService {
      /**
       * IK远程热更新字典接口
       */
      static getDicUsingGet(options: IRequestOptions = {}): Promise<string> {
        return new Promise((resolve, reject) => {
          let url = basePath + '/search/hot-words';
    
          const configs: IRequestConfig = getConfigs('get', 'application/json', url, options);
    
          let data = null;
    
          configs.data = data;
          axios(configs, resolve, reject);
        });
      }
      /**
       * 索引历史数据更新
       */
      static updateByQueryUsingPost(
        params: {
          /** indexNames */
          indexNames?: string;
        } = {} as any,
        options: IRequestOptions = {}
      ): Promise<any> {
        return new Promise((resolve, reject) => {
          let url = basePath + '/search/hot-words';
    
          const configs: IRequestConfig = getConfigs('post', 'application/json', url, options);
          configs.params = { indexNames: params['indexNames'] };
          let data = null;
    
          configs.data = data;
          axios(configs, resolve, reject);
        });
      }
    }
    
    export class IndexControllerService {
      /**
       * 创建初始化索引
       */
      static createIndexAndInitUsingPost(
        params: {
          /** ip */
          ip: string;
          /** moduleName */
          moduleName?: string;
          /** port */
          port: number;
        } = {} as any,
        options: IRequestOptions = {}
      ): Promise<any> {
        return new Promise((resolve, reject) => {
          let url = basePath + '/search/index';
    
          const configs: IRequestConfig = getConfigs('post', 'application/json', url, options);
          configs.params = { ip: params['ip'], moduleName: params['moduleName'], port: params['port'] };
          let data = null;
    
          configs.data = data;
          axios(configs, resolve, reject);
        });
      }
      /**
       * 删除索引
       */
      static deleteIndexUsingDelete(
        params: {
          /** moduleName */
          moduleName: string;
        } = {} as any,
        options: IRequestOptions = {}
      ): Promise<any> {
        return new Promise((resolve, reject) => {
          let url = basePath + '/search/index';
    
          const configs: IRequestConfig = getConfigs('delete', 'application/json', url, options);
          configs.params = { moduleName: params['moduleName'] };
          let data = null;
    
          configs.data = data;
          axios(configs, resolve, reject);
        });
      }
      /**
       * 删除索引数据
       */
      static deleteIndexContentByQueryUsingDelete(
        params: {
          /** moduleName */
          moduleName: string;
        } = {} as any,
        options: IRequestOptions = {}
      ): Promise<any> {
        return new Promise((resolve, reject) => {
          let url = basePath + '/search/index/content';
    
          const configs: IRequestConfig = getConfigs('delete', 'application/json', url, options);
          configs.params = { moduleName: params['moduleName'] };
          let data = null;
    
          configs.data = data;
          axios(configs, resolve, reject);
        });
      }
    }
    
    export interface AutoCompleteDto {
      /**  */
      indexNames?: string[];
    
      /**  */
      keyWord?: string;
    
      /**  */
      searchField?: string;
    
      /**  */
      size?: number;
    
      /**  */
      sortField?: string;
    }
    
    export interface JsonDataSourceDto {
      /**  */
      dataJson?: string;
    
      /**  */
      indexName?: string;
    
      /**  */
      mappings?: string;
    
      /**  */
      primaryKey?: string;
    }
    
    export interface SearchLogResultDTO {
      /**  */
      content?: string;
    
      /**  */
      docBoostScore?: number;
    
      /**  */
      extraPrimaryContent?: string;
    
      /**  */
      extraSecondaryContent?: string;
    
      /**  */
      lastUpdateTime?: Date;
    
      /**  */
      lastUpdateTimeIntValue?: string;
    
      /**  */
      moduleKey?: string;
    
      /**  */
      moduleName?: string;
    
      /**  */
      moduleShowName?: string;
    
      /**  */
      operationTime?: Date;
    
      /**  */
      operationType?: string;
    
      /** 二级模块显示名称 */
      secondaryModuleShowName?: string;
    
      /**  */
      title?: string;
    }
    
    export interface SearchParamDto {
      /**  */
      indexNames?: string;
    
      /**  */
      keyWord?: string;
    
      /**  */
      pageIndex?: number;
    
      /**  */
      pageSize?: number;
    }
    
    export interface SearchResultDTO {
      /**  */
      keyWords?: string;
    
      /**  */
      pageIndex?: number;
    
      /**  */
      pageSize?: number;
    
      /**  */
      resultCollection?: object[];
    
      /**  */
      searchTime?: number;
    
      /**  */
      summary?: object;
    
      /**  */
      totalCount?: string;
    
      /**  */
      totalPage?: number;
    }
    
    export interface SearchResultDTO_SearchLogResultDTO {
      /**  */
      keyWords?: string;
    
      /**  */
      pageIndex?: number;
    
      /**  */
      pageSize?: number;
    
      /**  */
      resultCollection?: SearchLogResultDTO[];
    
      /**  */
      searchTime?: number;
    
      /**  */
      summary?: object;
    
      /**  */
      totalCount?: string;
    
      /**  */
      totalPage?: number;
    }
    
    export interface TransportAddress {
      /**  */
      address?: string;
    
      /**  */
      port?: number;
    }
    
    export interface 索引总览信息 {
      /** 文件总数 */
      docsCount?: string;
    
      /** 索引详情 */
      indexDetailList?: 索引详情[];
    
      /** 索引存储总大小 */
      storageSizeTotal?: number;
    }
    
    export interface 索引详情 {
      /** 是否支持删除 */
      canDelete?: boolean;
    
      /** 文件数量 */
      docsCount?: string;
    
      /** 索引名 */
      indexName?: string;
    
      /** 索引存储大小(kb) */
      storageSize?: number;
    }

    如上红色部分是生成后的文件上手动新加的,可用来将axios替换成自己配置好的(带有拦截器等)

    比如我的request

    import axios from 'axios'
    import { UserModule } from '@/store/modules/user'
    import { tokenStorage } from '@/utils/storage'
    import { openLoading, closeLoading } from '@/utils/util'
    import QS from 'qs'
    import Vue from 'vue'
    // import { MainModule as AppModule } from '@main/store/app'
    // import { loginExpired } from './webViewApi'
    
    const type = (obj: any) =>
      Object.prototype.toString
        .call(obj)
        .slice(8, -1)
        .toLowerCase()
    
    interface IStatusStrategy {
      [prop: number]: () => void
    }
    interface ITypeStrategy {
      [prop: string]: (error: any) => void
    }
    
    const request = axios.create({ timeout: 150000000 })
    let messageError: any
    
    const requestConfig = async (config: any) => {
      if (!config.headers.Authorization && tokenStorage.get() && !config.url.includes('oauth/captcha')) {
        // 表示非登录请求
        config.headers['Authorization'] = 'Bearer ' + tokenStorage.get() // 让每个请求携带自定义token 请根据实际情况自行修改
      }
      if (config.method === 'get') {
        config.paramsSerializer = function(params: any) {
          return QS.stringify(params, { arrayFormat: 'repeat' })
        }
      }
      return config
    }
    const responseRes = (res: any) => {
      const code = res.status
      if (code !== 200) {
        Vue.prototype.$message.success(res.statusText)
        return res
      } else {
        return res
      }
    }
    
    const statusStrategy: IStatusStrategy = {
      500() {
        messageError('服务器请求失败')
      },
      502() {
        messageError('网关不可用')
      },
      503() {
        messageError('服务不可用')
      },
      504() {
        messageError('网关超时')
      },
      401() {
        messageError('登录超时,请重新登录!', 3000)
        UserModule.setLoginExpired(true)
      },
      404() {
        messageError('地址无效')
      }
    }
    
    const typeStrategy: ITypeStrategy = {
      arraybuffer(error) {
        const enc = new TextDecoder('utf-8')
        const err = JSON.parse(enc.decode(new Uint16Array(error.response.data))).error
        messageError(err, 5000)
      },
      blob(error) {
        const reader = new FileReader()
        reader.onload = (e: any) => {
          try {
            const data = JSON.parse(e.target.result)
            messageError(data.error || '系统错误,请联系管理员', 5000)
          } catch (error) {
            messageError(e.target.result || '系统错误,请联系管理员', 5000)
          }
        }
        reader.readAsText(error.response.data)
      }
    }
    
    const statusHandler = (error: any) => {
      const status = error?.response.status
      if (!statusStrategy[status]) return
      statusStrategy[status]()
      return true
    }
    const typeHandler = (error: any) => {
      const errType = type(error?.response.data)
      if (typeStrategy[errType]) {
        typeStrategy[errType](error)
      } else {
        const errMsg = error?.response.data.error_description || error?.response.data.error
        messageError(errMsg || '系统错误,请联系管理员', 5000)
      }
    }
    
    const responseError = (error: any) => {
      messageError = Vue.prototype.$message.error
      if (!error.message.includes('timeout')) statusHandler(error) || typeHandler(error)
      return Promise.reject(error)
    }
    
    request.interceptors.request.use(
      (config: any) => {
        openLoading()
        return requestConfig(config)
      },
      (error: any) => {
        closeLoading()
        Promise.reject(error)
      }
    )
    
    request.interceptors.response.use(
      (res: any) => {
        closeLoading()
        return responseRes(res)
      },
      (error: any) => {
        closeLoading()
        return responseError(error)
      }
    )
    
    export { request }
     以上就生成了,直接调用即可,如有不懂可加vx:844271163 备注博客园
  • 相关阅读:
    3、总结
    三分及小例题
    约瑟夫问题的推导
    对于联通块的处理
    扩展欧几里得与二元不定方程
    js 阻止事件捕获
    原生xhr发送JSON
    $timeout
    Angularjs Ng_repeat中实现复选框选中并显示不同的样式
    为什么用Object.prototype.toString.call(obj)检测对象类型?
  • 原文地址:https://www.cnblogs.com/xiaohuizhang/p/15592356.html
Copyright © 2011-2022 走看看