aegis-dev-tools的使用

前言
aegis-dev-tools是一个辅助开发前端的工具包,用于根据后端接口文档生成前端封装api请求。

创建后端项目
要求使用swagger,且controler书写规范,输入输出类型,备注都要 合理,比如

package com.dshvv.myblogserver.controller;

import com.dshvv.myblogserver.model.entity.Teacher;
import com.dshvv.myblogserver.utils.JsonResult;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;

@RestController
@RequestMapping("/teacher")
public class TeacherController {

  @ApiOperation(value = "添加老师", notes = "添加老师的接口", produces = "application/json")
  @PostMapping
  public JsonResult save(Teacher teacher) {
    return JsonResult.success();
  }

  @ApiOperation(value = "获取老师", notes = "获取老师的接口", produces = "application/json")
  @GetMapping(path = "/{id}")
  public JsonResult get(@PathVariable int id) {
    Teacher t1 = new Teacher();
    t1.setId(202001);
    t1.setName("丁老师");
    t1.setAge(20);
    return JsonResult.success(t1);
  }

  @ApiOperation(value = "获取老师列表", notes = "获取老师列表的接口", produces = "application/json")
  @GetMapping()
  public JsonResult list() {
    Teacher t1 = new Teacher();
    t1.setId(202001);
    t1.setName("丁老师");
    t1.setAge(20);
    ArrayList teachers = new ArrayList();
    teachers.add(t1);
    return JsonResult.success(teachers);
  }

  @ApiOperation(value = "删除老师", notes = "删除老师的接口", produces = "application/json")
  @DeleteMapping
  public JsonResult delete(int id) {
    return JsonResult.success();
  }

}
package com.dshvv.myblogserver.controller;

import com.dshvv.myblogserver.model.entity.Teacher;
import com.dshvv.myblogserver.utils.JsonResult;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.HashMap;

@RequestMapping
@RestController
public class OtherController {

  @ApiOperation(value = "后端服务起始页", notes = "用于用查看后端服务是否启动", produces = "text/html")
  @GetMapping("/")
  public ModelAndView Home() {
    return new ModelAndView("home");
  }

  @ApiOperation(value = "测试接口", notes = "用于测试后台是否可被访问", produces = "application/json")
  @GetMapping("/test")
  public JsonResult test() {
    return JsonResult.success();
  }
}

创建前端项目
要求用ts创建vue项目

 vue create vuetseg

开始使用
前端依赖依赖包

npm install aegis-api-proxy aegis-dev-tools

根目录增加配置文件api.config.js

module.exports = {
    templates: {},
    configs: [{
      url: 'http://localhost:7777/v2/api-docs', // 后端swagger地址
      typeParameterReflects: [{
        name: 'KeyValue',
        typeProperties: ['key', 'value']
      }, {
        name: 'JsonResult',
        typeProperties: ['data']
      }, {
        name: 'Page',
        typeProperties: ['content']
      }, {
        name: 'SimplePage',
        typeProperties: ['list']
      }, {
        name: 'Pair',
        typeProperties: ['first', 'second']
      }, {
        name: 'RequestValues',
        typeProperties: ['data']
      }]
    }],
    typesAsAny: ['JSONArray', 'Serializable', 'JSONObject'],
    unwrapTypes: ['Response', 'ResponseSimpleEnum', 'JsonResult']
  };

新增文件夹
根目录下,新增文件夹api、types

生成代码
packge.json的script增加如下代码

"api": "generate-api"

打开终端,执行

npm run api

此时,打开api、types两个文件夹,即可发现接口以及接口所需的类型文件都已经生成
但是此时还是不能使用,仍然需要继续配置

配置使用
如上,单纯的生成是不能使用的,还需要额外的配置
新增一个配置文件,configapibase.config.ts。当然在任意位置和文件名,无特定要求
然后内容如下

import {Global} from 'aegis-api-proxy';
import apiObj from './api-definition';

// ajax请求的基本配置
const config = {
  pathSuffix: '',
  basePath: 'http://localhost:7777',
  httpStatusErrorHandler: () => {
    return true;
  },
  logicErrorHandler: () => {
    return true;
  }
};

export default Global.proxyAPI(apiObj, config, {
  headers: {common: {}}
});

将此文件引入main.js中

import './config/apibase.config'

自此,已经全部配置准备完毕

然后还要新增全局类型文件(用于扩展自己自定义的api定义)
src ypesapi.d.ts

import {GeneratedApis} from './api-definition';

declare module'aegis-api-proxy' {

  // import {GenericAPI} from 'aegis-api-proxy';

  interface ApiObject<T> extends GeneratedApis<T> {
    // aaa: GenericAPI<any>;
  }

}

测试验证
app.vue修改如下

<template>
  <div class="app">
    <button @click="test">测试</button>
  </div>
</template>

<script lang="ts">
  import {Component, Vue} from 'vue-property-decorator';

  @Component
  export default class HelloWorld extends Vue {
    private async test() {
      const res: any = await this.$api.teacher.get.requestData(1);
      console.log(res);
    }
  }
</script>



其他



react的使用
react使用的时候,请修改配置如下

I think this plug-in works very well because it doesn't have to encapsulate HTTP requests by itself, and it also has type files.
Vue can be used directly, but React or Angular needs some extra work.
First, enter the plug-in root directory, "aegis-dev-tools/"
create profile tsconfig.json

{
  "compilerOptions": {
   "outDir": "./dist",
    "target": "es5",
    "module": "commonjs",
    "lib": [
      "es5",
      "es2016.array.include",
      "dom"
    ], 
    "strict": true,
    "esModuleInterop": true
  }
}

Then execute the tsc command

After the dist content is generated, go to distglobal index.js In the directory, comment out the Vue related code, and the modified version is as follows:

"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var api_proxy_1 = __importDefault(require("../api-proxy"));
var axios_1 = __importDefault(require("axios"));
// var vue_1 = __importDefault(require("vue"));
var apiProxy = function (apiObject, config, axiosConfig) {
    axios_1.default.defaults.baseURL = config.basePath;
    var apiProxy = api_proxy_1.default(apiObject, config, axiosConfig || { url: null });
    // var plugin = {
    //     installed: false,
    //     install: function (vue) {
    //         if (plugin.installed) {
    //             return;
    //         }
    //         if (!vue.prototype.$api) {
    //             Object.defineProperties(vue.prototype, {
    //                 $api: {
    //                     get: function () {
    //                         return apiProxy;
    //                     }
    //                 }
    //             });
    //         }
    //     }
    // };
    // vue_1.default.use(plugin);
    return apiProxy;
};
exports.default = {
    proxyAPI: apiProxy
};

At last packge.json Revision of export documents

"main": "dist/index.js",

demo:

import React,{useState, useEffect} from 'react';
import style from './style.less';
import api from '@/api/apibase-config'
export default (props: any)=> {
    useEffect(()=>{
      courtrealdata();
    },[]);

    const courtrealdata = async ()=>{
      const res = await api.api.real.v2.courtrealdata.courtRealData.req();
      console.log(res)
    }
    
    return (
        <div className={style.Home}>
          123
        </div>
    );
};

如果不想如上修改,或可以直接安装我修改二次封装过的包

npm install git+https://gitee.com/dshvv/aegis-api-proxy.git



原文地址:https://www.cnblogs.com/dshvv/p/13323943.html