excuteTest.vue 5.55 KB
<template>
  <div v-if="showTestFlag" class="mt-8">
    <div>
      <Button @click="handleExcute" type="primary"> 执行测试请求 </Button>
    </div>
    <div class="mt-8">
      <a-row type="flex" justify="center">
        <a-col :span="24">
          <a-textarea
            disabled
            v-if="isWebSocketType === '2'"
            allow-clear
            show-count
            v-model:value="testResult"
            placeholder="测试结果为:"
            :rows="8"
          />
          <a-textarea
            disabled
            v-else
            allow-clear
            show-count
            v-model:value="httpResult"
            placeholder="测试结果为:"
            :rows="8"
          />
        </a-col>
      </a-row>
    </div>
  </div>
</template>
<script lang="ts" setup name="testRequest">
  import { nextTick, ref, reactive, onUnmounted } from 'vue';
  import { Button } from 'ant-design-vue';
  import { otherHttp } from '/@/utils/http/axios';
  import { useWebSocket } from '@vueuse/core';
  import { JWT_TOKEN_KEY } from '/@/enums/cacheEnum';
  import { getAuthCache } from '/@/utils/auth';
  import { useUtils } from '../../../hooks/useUtils';

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

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

  const showTestFlag = ref(false);

  const token = getAuthCache(JWT_TOKEN_KEY);

  const socketUrls = ref('');

  const socketMessage: any = reactive({
    server: ``,
    sendValue: {
      tsSubCmds: [],
    },
  });

  //格式化替换像"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 testResult = ref('');

  const httpResult = ref('');

  const isWebSocketType = ref('');

  //执行测试接口
  const handleExcute = () => {
    emits('emitExcute');
    getValue();
  };

  const getValue = async () => {
    await nextTick();
    //获取Params和Header和Body
    const Objects = props.data;
    isWebSocketType.value = Objects?.method;
    const apiType = Objects?.apiType;
    const url = Objects?.apiGetUrl;
    const headers = Objects?.Header?.params;
    const params = Objects?.Params?.params;
    const body = Objects?.Body?.params;
    const apiUrl = url?.restfulFormat(params);
    if (isWebSocketType.value === '2') {
      socketUrls.value = url;
      socketMessage.server = `${socketUrls.value}?token=${token}`;
      const list = Object.values(params);
      const isEmpty = list.some((it) => it === '' || null || undefined);
      if (!isEmpty) {
        websocketRequest(params);
      } else {
        resetValue(false);
      }
    } else {
      const resp = await otherHttpRequest(apiType, apiUrl?.split('{?')[0], headers, params, body);
      if (!resp) return;
      httpResult.value = JSON.stringify(resp);
    }
  };

  //websocket请求
  const websocketRequest = (params, destroy = false) => {
    //websocket请求
    Reflect.deleteProperty(params, 'deviceProfileId');
    Reflect.deleteProperty(params, 'organizationId');
    Reflect.set(params, 'cmdId', 1);
    Reflect.set(params, 'scope', 'LATEST_TELEMETRY');
    Reflect.set(params, 'entityType', 'DEVICE');
    socketMessage.sendValue.tsSubCmds.push(params);
    const { send, close } = useWebSocket(socketMessage.server, {
      onConnected() {
        send(JSON.stringify(socketMessage.sendValue));
        console.log('建立连接了');
      },
      onMessage(_, e) {
        const { data } = JSON.parse(e.data);
        testResult.value = JSON.stringify(data);
      },
      onDisconnected() {
        console.log('断开连接了');
        close();
      },
      onError() {},
    });
    if (destroy) close();
  };

  onUnmounted(() => {
    if (isWebSocketType.value === '2') {
      websocketRequest(null, true);
    }
  });

  //TODO: 待优化 项目自带第三方请求
  const otherHttpRequest = async (
    apiType,
    apiUrl,
    headers = {},
    params = {},
    body,
    joinPrefix = false
  ) => {
    switch (apiType) {
      case 'GET':
        return await otherHttp.get(
          { url: apiUrl, params, headers },
          {
            apiUrl: '',
            joinPrefix,
          }
        );
      case 'POST':
        const { convertObj } = useUtils();
        return await otherHttp.post(
          { url: `${apiUrl}?${convertObj(params)}`, data: body, headers },
          {
            apiUrl: '',
            joinPrefix,
          }
        );
      case 'PUT':
        return await otherHttp.put(
          { url: apiUrl, data: body, headers, params },
          {
            apiUrl: '',
            joinPrefix,
          }
        );
    }
  };

  const resetValue = (flag) => {
    if (flag) {
      showTestFlag.value = false;
    }
    httpResult.value = '测试结果为:';
    testResult.value = '测试结果为:';
    isWebSocketType.value = '0';
  };

  const showTest = () => (showTestFlag.value = true);

  defineExpose({
    resetValue,
    showTest,
  });
</script>

<style scoped lang="less">
  :deep(.ant-input-textarea-show-count) {
    width: 30vw;
  }
</style>