excuteTest.vue 9.02 KB
<template>
  <div v-if="showTestFlag" class="mt-8">
    <div>
      <a-row>
        <Button @click="handleExcute" type="primary"> 执行测试请求 </Button>
      </a-row>
      <div v-if="isShowTestResult" style="display: flex; justify-content: space-between">
        <a-row class="mt-8" type="flex" justify="center" align="middle">
          <a-col :span="3"> 测试地址 </a-col>
          <a-col :span="21">
            <Tag color="blue" style="width: 31.6vw; white-space: normal; height: auto">
              {{ apiUrl?.split('{?')[0] }}
            </Tag>
          </a-col>
        </a-row>
      </div>
    </div>
    <div class="mt-8">
      <a-row type="flex" justify="space-between" align="middle">
        <a-col :span="24">
          <div>
            <JsonEditor
              :showBtn="true"
              v-if="isWebSocketType === '2'"
              style="width: 40vw; height: 40vh"
              ref="jsonWebsocketEditorRef"
            />
            <JsonEditor
              :showBtn="true"
              v-else
              style="width: 40vw; height: 40vh"
              ref="jsonEditorRef"
            />
          </div>
        </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 { useUtils } from '../../../hooks/useUtils';
  import JsonEditor from '../../SimpleRequest/components/jsonEditor.vue';
  import { Tag } from 'ant-design-vue';
  import { useThrottleFn } from '@vueuse/shared';

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

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

  const showTestFlag = ref(false);

  const jsonEditorRef = ref<InstanceType<typeof JsonEditor>>();

  const jsonWebsocketEditorRef = ref<InstanceType<typeof JsonEditor>>();

  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 isWebSocketType = ref('');

  const isToken = ref('');

  const apiUrl = ref('');

  const isPostToken = ref('');

  const isShowTestResult = ref(false);

  const postBodyType = ref('');

  //执行测试接口
  const handleExcute = () => {
    emits('emitExcute');
    useThrottle();
    isShowTestResult.value = true;
  };

  const useThrottle = useThrottleFn(() => {
    getValue();
  }, 2000);

  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;
    isToken.value = Objects?.Params?.token;
    const body = Objects?.Body?.params;
    isPostToken.value = Objects?.Body?.token;
    postBodyType.value = Objects?.Body?.type;
    apiUrl.value = url?.restfulFormat(params);
    if (isWebSocketType.value === '2') {
      socketUrls.value = url;
      socketMessage.server = `${socketUrls.value}?token=${isToken.value}`;
      const list = Object.values(params);
      const isEmpty = list.some((it) => it === '' || null || undefined);
      if (!isEmpty) {
        websocketRequest(params);
      } else {
        resetValue(false);
      }
    } else {
      try {
        const resp = await otherHttpRequest(
          apiType,
          apiUrl.value?.split('{?')[0],
          headers,
          params,
          body,
          isToken.value,
          isPostToken.value,
          postBodyType.value
        );
        if (!resp) return;
        if (Object.prototype.toString.call(resp) === '[object Object]') {
          jsonEditorRef.value?.setJsonValue(resp);
        } else if (typeof resp === 'string') {
          jsonEditorRef.value?.setJsonValue(resp);
        } else if (Array.isArray(resp)) {
          const temp = {
            data: resp,
          };
          jsonEditorRef.value?.setJsonValue(temp);
        } else {
          jsonEditorRef.value?.setJsonValue(JSON.stringify(resp));
        }
      } catch (e) {
        if (Object.prototype.toString.call(e) === '[object Object]') {
          jsonEditorRef.value?.setJsonValue(e);
        } else {
          jsonEditorRef.value?.setJsonValue('404未找到资源');
        }
      }
    }
  };

  //websocket请求
  const websocketRequest = (params, destroy = false) => {
    //websocket请求
    if (Object.prototype.toString.call(params) === '[object Object]') {
      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);
        if (Object.prototype.toString.call(data) === '[object Object]') {
          jsonWebsocketEditorRef.value?.setJsonValue(data);
        } else if (typeof data === 'string') {
          jsonWebsocketEditorRef.value?.setJsonValue(data);
        } else if (Array.isArray(data)) {
          jsonWebsocketEditorRef.value?.setJsonValue(JSON.stringify(data));
        } else {
          jsonEditorRef.value?.setJsonValue(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,
    token,
    postToken,
    postBodyType,
    joinPrefix = false
  ) => {
    const { convertObj } = useUtils();
    switch (apiType) {
      case 'GET':
        const objGet = Object.assign(
          {},
          {
            'X-Authorization': `Bearer ${!token ? postToken : token}`,
          },
          headers
        );
        return await otherHttp.get(
          { url: apiUrl, params, headers: objGet },
          {
            apiUrl: '',
            joinPrefix,
            withToken: false,
            errorMessageMode: 'none',
          }
        );
      case 'POST':
        const objPost = Object.assign(
          {},
          {
            'X-Authorization': `Bearer ${!postToken ? token : postToken}`,
          },
          {
            'Content-Type':
              postBodyType === 'xml'
                ? 'text/xml'
                : postBodyType === 'form-data'
                ? 'multipart/form-data'
                : postBodyType === 'x-www-form-urlencoded'
                ? 'application/x-www-form-urlencoded'
                : postBodyType === 'json'
                ? 'application/json'
                : 'application/json',
          },
          headers
        );
        return await otherHttp.post(
          { url: `${apiUrl}?${convertObj(params)}`, data: body, headers: objPost },
          {
            apiUrl: '',
            joinPrefix,
            withToken: false,
            errorMessageMode: 'none',
          }
        );
      case 'PUT':
        const objPut = Object.assign({}, headers, {
          'X-Authorization': `Bearer ${!postToken ? token : postToken}`,
        });
        return await otherHttp.put(
          { url: `${apiUrl}?${convertObj(params)}`, data: body, headers: objPut, params },
          {
            apiUrl: '',
            joinPrefix,
            withToken: false,
            errorMessageMode: 'none',
          }
        );
    }
  };

  const resetValue = (flag) => {
    if (flag) {
      showTestFlag.value = false;
    }
    nextTick(() => {
      jsonEditorRef.value?.setJsonValue('测试结果为');
      jsonWebsocketEditorRef.value?.setJsonValue('测试结果为');
    });
    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>