index.vue 4.99 KB
<template>
  <div>
    <div class="mt-8">
      <div>
        <Button @click="handleTest" type="primary"> 测试接口 </Button>
      </div>
      <div v-if="showTestEditCell" class="mt-8">
        <a-row type="flex" justify="center">
          <a-col :span="3"> 参数设置 </a-col>
          <a-col :span="21">
            <TestEditCellTable ref="testEditCellTableRef" :method="method" />
          </a-col>
        </a-row>
      </div>
    </div>
    <div v-if="showTestEditCell" class="mt-8">
      <div>
        <Button @click="handleExcute" type="primary"> 执行 </Button>
      </div>
      <div class="mt-8">
        <a-row type="flex" justify="center">
          <a-col :span="3"> 测试结果 </a-col>
          <a-col :span="21">
            <a-textarea
              allow-clear
              show-count
              v-model:value="testResult"
              placeholder="测试结果为:"
              :rows="8"
            />
          </a-col>
        </a-row>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup name="testRequest">
  import { ref, nextTick } from 'vue';
  import { Button } from 'ant-design-vue';
  import { TestEditCellTable } from '../TestEditCellTable/index';
  import { otherHttp } from '/@/utils/http/axios';

  const emits = defineEmits(['testInterface']);

  const props = defineProps({
    method: {
      type: String,
    },
    data: {
      type: Object,
    },
  });

  const showTestEditCell = ref(false);

  const testEditCellTableRef = ref<InstanceType<typeof TestEditCellTable>>();

  const testResult = ref('');

  // const testNeedKeys = ['organizationId', 'deviceProfileId', 'entityId', 'keys', 'date'];

  const handleTest = () => {
    showTestEditCell.value = true;
    emits('testInterface');
    getValue();
  };

  //获取多个key
  const getMultipleKeys = (list) => {
    let temps = [];
    list?.forEach((it) => {
      const keys = it.key.split(',');
      const temp = keys.map((item) => {
        let obj: { key: string; value: string } = { key: '', value: '' };
        obj.key = item;
        obj.value = item === 'scope' ? it.value : '';
        return obj;
      });
      temps = temp;
    });
    return temps;
  };

  //获取测试表格的key value 数组对象形式
  const getTestTableKeyValue = () => {
    return testEditCellTableRef.value?.getValue().map((it) => {
      const value = it.key === 'scope' ? it.keyValue : it.value;
      const key = it.key === 'scope' ? it.value : it.key;
      return {
        key,
        value,
      };
    });
  };

  //格式化"http:xxxx/api/xx/{xx}/{xx}/{xx}这种格式"
  String.prototype.restfulFormat = function (replacements) {
    var formatString = function (str, replacements) {
      replacements =
        typeof replacements === 'object' ? replacements : Array.prototype.slice.call(arguments, 1);
      return str.replace(/\{\{|\}\}|\{(\w+)\}/g, function (m, n) {
        if (m == '{{') {
          return '{';
        }
        if (m == '}}') {
          return '}';
        }
        return replacements[n];
      });
    };
    replacements =
      typeof replacements === 'object' ? replacements : Array.prototype.slice.call(arguments, 0);
    return formatString(this, replacements);
  };

  //项目自带第三方请求
  const otherHttpRequest = async (apiType, params = {}, api, joinPrefix = false) => {
    console.log(params);
    switch (apiType) {
      case 'get':
        return await otherHttp.get(
          { url: api },
          {
            apiUrl: '',
            joinPrefix,
          }
        );
    }
  };

  const getValue = async () => {
    await nextTick();
    await nextTick(() => {
      const getSingleKey = props.data?.list?.filter((it: any) => it.key.split(',').length === 1);
      const getMuteKey = props.data?.list?.filter((it: any) => it.key.split(',').length > 1);
      const getMuteKeys = getMultipleKeys(getMuteKey);
      const getSingleKeys = getMultipleKeys(getSingleKey);
      const mergeKeys = [...getSingleKeys, ...getMuteKeys];
      testEditCellTableRef.value?.setTableArray(mergeKeys);
    });
  };

  //执行测试接口
  const handleExcute = async () => {
    await nextTick();
    await nextTick(async () => {
      const getTable = getTestTableKeyValue();
      const apiGetUrl = `${props.data?.requestOriginUrl}${props.data?.requestUrl}`;
      const apiType = props.data?.paramsType.toLowerCase();
      const getKeyValues = {};
      getTable?.map((it) => (getKeyValues[it.key!] = it.value!));
      const formatApi = apiGetUrl.restfulFormat(getKeyValues);
      const rest = await otherHttpRequest(apiType, {}, formatApi, false);
      if (!rest) return;
      testResult.value = rest;
    });
  };

  //设置数据
  const setValue = () => {
    showTestEditCell.value = false;
    testResult.value = '';
  };

  defineExpose({
    setValue,
    handleTest,
  });
</script>

<style scoped lang="less"></style>