swagger文档管理改为API接口文档管理

This commit is contained in:
暮光:城中城
2021-11-26 23:51:14 +08:00
parent 4408525b45
commit 91aef6f9f4
165 changed files with 3892 additions and 5744 deletions

View File

@@ -0,0 +1,68 @@
<template>
<a-card>
<a-form :label-col="{span: 4}" :wrapper-col="{span: 20}" v-if="swaggerDocInfo">
<a-form-item label="标题">{{swaggerDocInfo.title}}</a-form-item>
<a-form-item label="版本">{{swaggerDocInfo.version}}</a-form-item>
<a-form-item label="作者" v-if="swaggerDocInfo.contact">
<template v-if="swaggerDocInfo.contact.name">
{{swaggerDocInfo.contact.name}}
</template>
<template v-if="swaggerDocInfo.contact.email">
<a-divider type="vertical" />{{swaggerDocInfo.contact.email}}
</template>
<template v-if="swaggerDocInfo.contact.url">
<a-divider type="vertical" />
<a :href="swaggerDocInfo.contact.url" target="_blank">{{swaggerDocInfo.contact.url}}</a>
</template>
</a-form-item>
<a-form-item label="host">{{swaggerDoc.host}}</a-form-item>
<a-form-item label="许可证" v-if="swaggerDocInfo.license">
<a :href="swaggerDocInfo.license.url" target="_blank">{{swaggerDocInfo.license.name}}</a>
</a-form-item>
<a-form-item label="服务条款" v-if="swaggerDocInfo.termsOfService">
<a :href="swaggerDocInfo.termsOfService" target="_blank">{{swaggerDocInfo.termsOfService}}</a>
</a-form-item>
<a-form-item label="文档说明">
<div class="markdown-body" v-html="getDescription(swaggerDocInfo.description)"></div>
</a-form-item>
<a-form-item label="接口统计">
<a-row :gutter="[16, 16]">
<template v-for="method in ['get', 'post', 'put', 'delete', 'head', 'patch', 'options', 'trace', 'total']">
<a-col :span="6" v-if="methodStatistic[method]">
<a-card size="small">
<a-statistic :title="method === 'total'?'总计':method.toUpperCase() + '方法'" :value="methodStatistic[method]" suffix="个"></a-statistic>
</a-card>
</a-col>
</template>
</a-row>
</a-form-item>
</a-form>
<div v-else style="text-align: center;">暂无文档信息请先选择文档</div>
</a-card>
</template>
<script>
import { toRefs, ref, reactive, onMounted, computed } from 'vue';
import {useStore} from 'vuex';
import {markdownIt} from 'mavon-editor'
import 'mavon-editor/dist/markdown/github-markdown.min.css'
import 'mavon-editor/dist/css/index.css'
export default {
setup() {
const store = useStore()
const swaggerDoc = computed(() => store.state.swaggerDoc);
const swaggerDocInfo = computed(() => store.state.swaggerDoc.info);
const methodStatistic = computed(() => store.state.methodStatistic);
const getDescription = description => {
return markdownIt.render(description || '');
};
return {
swaggerDoc,
swaggerDocInfo,
methodStatistic,
getDescription,
};
},
};
</script>

View File

@@ -0,0 +1,109 @@
<template>
<template v-if="isLoadSuccess">
<a-tabs v-model:activeKey="activePage" closable @tab-click="changePage" style="padding: 5px 10px 0;">
<a-tab-pane tab="接口说明" key="doc">
<DocContent :docInfoShow="docInfoShow" :requestParamList="requestParamList" :responseParamList="responseParamList"></DocContent>
</a-tab-pane>
<a-tab-pane tab="在线调试" key="debug">
<DocDebugger :docInfoShow="docInfoShow" :requestParamList="requestParamList" :responseParamList="responseParamList"></DocDebugger>
</a-tab-pane>
</a-tabs>
</template>
<a-spin v-else tip="文档数据加载中...">
<div style="padding: 20px 0;height: 100px;"></div>
</a-spin>
</template>
<script>
import {toRefs, ref, reactive, onMounted, watch} from 'vue';
import { useRouter, useRoute } from "vue-router";
import {useStore} from 'vuex';
import { message } from 'ant-design-vue';
import { onBeforeRouteLeave, onBeforeRouteUpdate } from 'vue-router'
import swaggerAnalysis from '../../assets/core/SwaggerAnalysis.js'
import DocContent from './docView/DocContent.vue'
import DocDebugger from './docView/DocDebugger.vue'
import {markdownIt} from 'mavon-editor'
import 'mavon-editor/dist/markdown/github-markdown.min.css'
import 'mavon-editor/dist/css/index.css'
export default {
components: { DocContent, DocDebugger },
setup() {
const route = useRoute();
const store = useStore();
let activePage = ref('doc');
let requestParamList = ref([]);
let responseParamList = ref([]);
let docInfoShow = ref({
url: '',
description: '',
method: '',
consumes: '',
produces: '',
});
let isLoadSuccess = ref(false);
let intervalNum = 0;
let intervalTimer = undefined;
const initLoadDocument = () => {
let path = route.query.path + '.' + route.query.method;
if (Object.keys(store.state.swaggerUrlMethodMap).length <= 0) {
console.log('文档尚未加载,等待加载完成');
if (!intervalTimer) {
intervalTimer = setInterval(() => {
if (isLoadSuccess.value || intervalNum++ > 50) {
clearInterval(intervalTimer);
return;
}
if (Object.keys(store.state.swaggerUrlMethodMap).length > 0) {
console.log('文档内容改变,重新加载文档');
initLoadDocument();
}
}, 1000);
}
return;
}
let docInfo = store.state.swaggerUrlMethodMap[path];
if (!docInfo) {
message.error('没有找到对应的文档');
return;
}
isLoadSuccess.value = true;
store.commit('addTableName', {key: route.fullPath, val: docInfo.summary});
// 解析接口说明
let consumes = '', produces = '';
if (docInfo.consumes && docInfo.consumes.length > 0) {
consumes = docInfo.consumes.join(' ');
}
if (docInfo.produces && docInfo.produces.length > 0) {
produces = docInfo.produces.join(' ');
}
let description = markdownIt.render(docInfo.description || docInfo.summary || '');
docInfoShow.value = {
url: docInfo.url,
description: description,
method: docInfo.method || '',
consumes: consumes,
produces: produces,
};
// 解析请求参数
let definitionsDataMap = store.state.swaggerDefinitions;
requestParamList.value = swaggerAnalysis.getRequestParamList(docInfo.parameters, definitionsDataMap);
responseParamList.value = swaggerAnalysis.getResponseParamList(docInfo.responses, definitionsDataMap);
}
onMounted(() => {
initLoadDocument();
});
const changePage = () => {
}
return {
docInfoShow,
activePage,
changePage,
isLoadSuccess,
requestParamList,
responseParamList,
};
},
};
</script>

View File

@@ -0,0 +1,109 @@
<template>
<a-form :label-col="{span: 4}" :wrapper-col="{span: 20}">
<a-form-item label="接口地址">{{docInfoShow.url}}</a-form-item>
<a-form-item label="说明">
<div class="markdown-body" v-html="docInfoShow.description" v-highlight></div>
</a-form-item>
<a-form-item label="请求方式">{{docInfoShow.method}}</a-form-item>
<a-form-item label="请求数据类型">{{docInfoShow.consumes}}</a-form-item>
<a-form-item label="响应数据类型">{{docInfoShow.produces}}</a-form-item>
<a-form-item label="请求参数">
<a-table :dataSource="requestParamList" :columns="requestParamListColumns" size="small" :pagination="false" defaultExpandAllRows>
<template #bodyCell="{ column, text, record }">
<template v-if="column.dataIndex === 'type'">
{{text}}
<template v-if="record.subType">[{{record.subType}}]</template>
<template v-if="record.format">({{record.format}})</template>
</template>
<template v-if="column.dataIndex === 'in'">
<a-tag color="pink" v-if="text === 'header'">header</a-tag>
<a-tag color="red" v-else-if="text === 'body'">body</a-tag>
<a-tag color="orange" v-else-if="text === 'query'">query</a-tag>
<a-tag color="green" v-else-if="text === 'formData'">formData</a-tag>
<template v-else-if="!text">-</template>
<a-tag color="purple" v-else>{{text}}</a-tag>
</template>
<template v-if="column.dataIndex === 'required'">
<span v-if="text === '是'" style="color: #f00;"></span>
<template v-else-if="text === '否'"></template>
<template v-else>-</template>
</template>
<template v-if="column.dataIndex === 'description'">
{{text}}
</template>
</template>
</a-table>
</a-form-item>
<a-form-item label="返回结果">
<a-table :dataSource="responseParamList" :columns="responseCodeListColumns" size="small" :pagination="false">
<template #bodyCell="{ column, text, record }">
<template v-if="column.dataIndex === 'desc'">
<div v-html="text"></div>
</template>
</template>
<template #expandedRowRender="{ record }">
<template v-if="record.schemas">
<a-table :dataSource="record.schemas" :columns="responseParamListColumns" size="small" :pagination="false">
<template #bodyCell="{ column, text, record }">
<template v-if="column.dataIndex === 'type'">
{{text}}
<template v-if="record.subType">[{{record.subType}}]</template>
<template v-if="record.format">({{record.format}})</template>
</template>
</template>
</a-table>
</template>
<div v-else style="text-align: center;padding: 10px 0;">无参数说明</div>
</template>
</a-table>
</a-form-item>
</a-form>
</template>
<script>
import {toRefs, ref, reactive, onMounted, watch} from 'vue';
import { useRouter, useRoute } from "vue-router";
import {useStore} from 'vuex';
import { message } from 'ant-design-vue';
import {markdownIt} from 'mavon-editor'
import 'mavon-editor/dist/markdown/github-markdown.min.css'
import 'mavon-editor/dist/css/index.css'
export default {
props: {
docInfoShow: {
type: Object,
required: true
},
requestParamList: {
type: Array,
required: true
},
responseParamList: {
type: Array,
required: true
},
},
setup() {
return {
requestParamListColumns: [
{title: '参数名', dataIndex: 'name', width: 200},
{title: '类型', dataIndex: 'type', width: 150},
{title: '参数位置', dataIndex: 'in', width: 100},
{title: '必填', dataIndex: 'required', width: 60},
{title: '说明', dataIndex: 'description'},
],
responseCodeListColumns: [
{title: '状态码', dataIndex: 'code', width: 100},
{title: '类型', dataIndex: 'type', width: 250},
{title: '说明', dataIndex: 'desc'},
],
responseParamListColumns: [
{title: '参数名', dataIndex: 'name', width: 250},
{title: '类型', dataIndex: 'type', width: 250},
{title: '说明', dataIndex: 'description'},
],
};
},
};
</script>

View File

@@ -0,0 +1,330 @@
<template>
<div>
<a-input-search :addon-before="docInfoShow.method.toUpperCase()" v-model:value="docUrl" @search="sendRequest" placeholder="请输入目标URL地址">
<template #enterButton>
<a-button type="primary" :loading="requestLoading">{{isDownloadRequest?'下载文件':'发送请求'}}</a-button>
</template>
</a-input-search>
<a-tabs v-model:activeKey="activePage" closable @tab-click="activePageChange" style="padding: 5px 10px 0;">
<a-tab-pane tab="URL参数" key="urlParam" forceRender>
<div v-show="queryParamVisible">
<ParamTable ref="urlParamRef" :paramList="urlParamList"></ParamTable>
</div>
</a-tab-pane>
<a-tab-pane tab="Body参数" key="bodyParam" v-if="docInfoShow.method !== 'get'" forceRender>
<div v-show="queryParamVisible">
<div style="margin-bottom: 6px;">
<a-radio-group v-model:value="bodyParamType">
<a-radio value="none">none</a-radio>
<a-radio value="form">form-data</a-radio>
<a-radio value="formUrlEncode">x-www-form-urlencoded</a-radio>
<a-radio value="row">row</a-radio>
<!-- <a-radio value="binary">binary</a-radio>-->
</a-radio-group>
<a-select v-if="bodyParamType === 'row'" v-model:value="consumesParamType" size="small" style="margin-left: 10px;vertical-align: top;width: 100px;">
<a-select-option value="json">JSON</a-select-option>
<a-select-option value="html">HTML</a-select-option>
<a-select-option value="xml">XML</a-select-option>
<a-select-option value="javascript">JavaScript</a-select-option>
<a-select-option value="text">TEXT</a-select-option>
</a-select>
</div>
<div v-show="bodyParamType === 'form'">
<ParamTable ref="formParamRef" :paramList="formParamList" showType></ParamTable>
</div>
<div v-show="bodyParamType === 'formUrlEncode'">
<ParamTable ref="formEncodeParamRef" :paramList="formEncodeParamList"></ParamTable>
</div>
<div v-show="bodyParamType === 'row'">
<ParamBody ref="bodyParamRef" :rowLang="consumesParamType" :paramList="bodyRowParamList"></ParamBody>
</div>
</div>
</a-tab-pane>
<a-tab-pane tab="Header参数" key="headerParam" forceRender>
<div v-show="queryParamVisible">
<ParamTable ref="headerParamRef" :paramList="headerParamList"></ParamTable>
</div>
</a-tab-pane>
<a-tab-pane tab="Cookie参数" key="cookieParam" forceRender>
<div v-show="queryParamVisible">
<ParamTable ref="cookieParamRef" :paramList="cookieParamList"></ParamTable>
</div>
</a-tab-pane>
<template #rightExtra>
<a-button v-if="queryParamVisible" @click="hideQueryParam" type="link">收起参数</a-button>
<a-button v-else @click="showQueryParam" type="link">展开参数</a-button>
</template>
</a-tabs>
<DocDebuggerResult v-if="!isDownloadRequest" :result="requestResult" :loading="requestLoading"></DocDebuggerResult>
<form method="post" ref="downloadFormRef" :action="downloadFormParam.url" target="_blank">
<input type="hidden" :name="key" :value="val" v-for="(val,key) in downloadFormParam.param">
</form>
</div>
</template>
<script>
import {toRefs, ref, reactive, onMounted, watch} from 'vue';
import { useRouter, useRoute } from "vue-router";
import {useStore} from 'vuex';
import { message } from 'ant-design-vue';
import {markdownIt} from 'mavon-editor'
import DocDebuggerResult from './DocDebuggerResult.vue'
import ParamTable from '../../../components/params/ParamTable.vue'
import ParamBody from '../../../components/params/ParamBody.vue'
import {CloseOutlined, VerticalAlignTopOutlined, VerticalAlignBottomOutlined} from '@ant-design/icons-vue';
import 'mavon-editor/dist/markdown/github-markdown.min.css'
import 'mavon-editor/dist/css/index.css'
import {zyplayerApi} from "../../../api";
import {getZyplayerApiBaseUrl} from "../../../api/request/utils.js";
export default {
props: {
docInfoShow: {
type: Object,
required: true
},
requestParamList: {
type: Array,
required: true
},
responseParamList: {
type: Array,
required: true
},
},
components: {
VerticalAlignTopOutlined, VerticalAlignBottomOutlined, CloseOutlined, ParamTable, ParamBody, DocDebuggerResult,
},
setup(props) {
const store = useStore();
let apiDoc = store.state.apiDoc || {};
let globalParam = store.state.globalParam || [];
let swaggerDoc = store.state.swaggerDoc || {};
let urlDomain = apiDoc.rewriteDomain || swaggerDoc.host;
let docUrl = ref(urlDomain + props.docInfoShow.url);
let activePage = ref('urlParam');
// URL参数处理
const urlParamRef = ref();
let urlParamListProp = props.requestParamList.filter(item => item.in === 'query' || item.in === 'path');
let urlParamList = ref([]);
// Header参数处理
const headerParamRef = ref();
let headerParamListGlobal = globalParam.filter(item => item.paramType === 2);
let headerParamListProp = props.requestParamList.filter(item => item.in === 'header');
let nextIndex = 1;
headerParamListGlobal.forEach(item => {
headerParamListProp.push({name: item.paramKey, value: item.paramValue, type: 'string', key: 'g' + (nextIndex++)});
});
let headerParamList = ref(JSON.parse(JSON.stringify(headerParamListProp)));
// cookie参数处理
const cookieParamRef = ref();
let cookieParamListGlobal = globalParam.filter(item => item.paramType === 3);
let cookieParamListProp = props.requestParamList.filter(item => item.in === 'cookie');
cookieParamListGlobal.forEach(item => {
cookieParamListProp.push({name: item.paramKey, value: item.paramValue, type: 'string', key: 'g' + (nextIndex++)});
});
let cookieParamList = ref(JSON.parse(JSON.stringify(cookieParamListProp)));
// form参数处理
const formParamRef= ref();
let formParamListGlobal = globalParam.filter(item => item.paramType === 1);
let formParamListProp = props.requestParamList.filter(item => item.in === 'formData');
formParamListGlobal.forEach(item => {
formParamListProp.push({name: item.paramKey, value: item.paramValue, type: 'string', key: 'g' + (nextIndex++)});
});
let formParamList = ref([]);
if (props.docInfoShow.method === 'post') {
// post的时候参数否放到form里面
formParamListProp = formParamListProp.concat(urlParamListProp);
} else {
// 否则放到URL参数里面
urlParamList = ref(JSON.parse(JSON.stringify(urlParamListProp)));
}
// form参数处理
const formEncodeParamRef = ref();
let formEncodeParamList = ref([]);
// body 参数
let bodyParamRef = ref();
let bodyParamType = ref('form');
let consumesParamType = ref('json');
let bodyRowListProp = props.requestParamList.filter(item => item.in === 'body');
let bodyRowParamList = ref(JSON.parse(JSON.stringify(bodyRowListProp)));
// x-www-form-urlencoded
if (props.docInfoShow.consumes.indexOf('application/x-www-form-urlencoded') >= 0) {
bodyParamType.value = 'formUrlEncode';
formEncodeParamList = ref(JSON.parse(JSON.stringify(formParamListProp)));
} else if (props.docInfoShow.consumes.indexOf('multipart/form-data') >= 0) {
bodyParamType.value = 'form';
formParamList = ref(JSON.parse(JSON.stringify(formParamListProp)));
} else if (props.docInfoShow.consumes.indexOf('application/json') >= 0) {
bodyParamType.value = 'row';
consumesParamType.value = 'json';
formEncodeParamList = ref(JSON.parse(JSON.stringify(formParamListProp)));
if (formParamListProp.length > 0) {
bodyParamType.value = 'formUrlEncode';
}
} else if (props.docInfoShow.consumes.indexOf('application/xml') >= 0 || props.docInfoShow.consumes.indexOf('text/xml') >= 0) {
bodyParamType.value = 'row';
consumesParamType.value = 'xml';
formEncodeParamList = ref(JSON.parse(JSON.stringify(formParamListProp)));
if (formParamListProp.length > 0) {
bodyParamType.value = 'formUrlEncode';
}
} else {
formParamList = ref(JSON.parse(JSON.stringify(formParamListProp)));
}
if (formParamList.value.length > 0) {
activePage.value = 'urlParam';
} else if (formParamListProp.length > 0 || bodyRowListProp.length > 0) {
activePage.value = 'bodyParam';
} else if (headerParamListProp.length > 0) {
activePage.value = 'headerParam';
}
// 发送请求
let requestResult = ref({});
let requestLoading = ref(false);
let downloadFormParam = ref({url: getZyplayerApiBaseUrl() + '/doc-swagger/proxy/download', param: {}});
let downloadFormRef = ref();
let isDownloadRequest = (props.docInfoShow.produces === 'application/octet-stream');
const sendRequest = () => {
if (!docUrl.value) {
message.error('请输入请求的目标URL地址');
return;
}
let formObjData = {};
const formData = new FormData();
let urlParamSelected = urlParamRef.value.getSelectedRowKeys();
let urlParamStr = urlParamList.value.filter(item => urlParamSelected.indexOf(item.key) >= 0 && item.name && item.value).map(item => {
formObjData[item.name] = item.value;
return item.name + '=' + encodeURIComponent(item.value);
}).join('&');
let headerParamSelected = headerParamRef.value.getSelectedRowKeys();
let headerParamArr = headerParamList.value.filter(item => headerParamSelected.indexOf(item.key) >= 0 && item.name && item.value).map(item => {
return {code: item.name, value: item.value};
});
let cookieParamSelected = cookieParamRef.value.getSelectedRowKeys();
let cookieParamArr = cookieParamList.value.filter(item => cookieParamSelected.indexOf(item.key) >= 0 && item.name && item.value).map(item => {
return {code: item.name, value: item.value};
});
let formParamArr = [];
if (formParamRef.value) {
let formParamSelected = formParamRef.value.getSelectedRowKeys();
formParamArr = formParamList.value.filter(item => formParamSelected.indexOf(item.key) >= 0 && item.name && item.value).map(item => {
// todo 判断处理文件格式
formObjData[item.name] = item.value;
return {code: item.name, value: item.value};
});
}
let formEncodeParamArr = [];
if (formEncodeParamRef.value) {
let formEncodeParamSelected = formEncodeParamRef.value.getSelectedRowKeys();
formEncodeParamArr = formEncodeParamList.value.filter(item => formEncodeParamSelected.indexOf(item.key) >= 0 && item.name && item.value).map(item => {
// todo 判断处理文件格式
formObjData[item.name] = item.value;
return {code: item.name, value: item.value};
});
}
let bodyParamStr = '';
if (bodyParamRef.value) {
bodyParamStr = bodyParamRef.value.getParam();
}
// fileList.value.forEach(file => {
// formData.append('files[]', file);
// });
let url = urlParamStr ? (docUrl.value + '?' + urlParamStr) : docUrl.value;
// 替换path参数
Object.keys(formObjData).forEach((key) => {
url = url.replace("{" + key + "}", formObjData[key]);
});
// 下载请求
if (isDownloadRequest) {
downloadFormParam.value.param = {
url: url,
host: urlDomain,
method: props.docInfoShow.method,
contentType: props.docInfoShow.consumes,
headerParam: JSON.stringify(headerParamArr),
cookieParam: JSON.stringify(cookieParamArr),
formParam: JSON.stringify(formParamArr),
formEncodeParam: JSON.stringify(formEncodeParamArr),
bodyParam: bodyParamStr,
};
setTimeout(() => downloadFormRef.value.submit(), 0);
} else {
// 正常请求
formData.append('url', url);
formData.append('host', urlDomain);
formData.append('method', props.docInfoShow.method);
formData.append('contentType', props.docInfoShow.consumes);
formData.append('headerParam', JSON.stringify(headerParamArr));
formData.append('cookieParam', JSON.stringify(cookieParamArr));
formData.append('formParam', JSON.stringify(formParamArr));
formData.append('formEncodeParam', JSON.stringify(formEncodeParamArr));
formData.append('bodyParam', bodyParamStr);
requestLoading.value = true;
requestResult.value = {};
zyplayerApi.requestUrl(formData).then(res => {
requestResult.value = res;
requestLoading.value = false;
}).catch(e => {
requestLoading.value = false;
});
}
};
let queryParamVisible = ref(true);
const hideQueryParam = () => {
queryParamVisible.value = false;
}
const showQueryParam = () => {
queryParamVisible.value = true;
}
const activePageChange = () => {
queryParamVisible.value = true;
}
return {
docUrl,
activePage,
activePageChange,
requestLoading,
sendRequest,
requestResult,
consumesParamType,
downloadFormParam,
downloadFormRef,
isDownloadRequest,
// url参数
urlParamRef,
urlParamList,
// header参数
headerParamRef,
headerParamList,
// cookie参数
cookieParamRef,
cookieParamList,
// form参数
formParamRef,
formParamList,
// form-encode参数
formEncodeParamRef,
formEncodeParamList,
// body参数
bodyParamRef,
bodyParamType,
bodyRowParamList,
responseCodeListColumns: [
{title: '状态码', dataIndex: 'code', width: 100},
{title: '类型', dataIndex: 'type', width: 250},
{title: '说明', dataIndex: 'desc'},
],
responseParamListColumns: [
{title: '参数名', dataIndex: 'name', width: 250},
{title: '类型', dataIndex: 'type', width: 250},
{title: '说明', dataIndex: 'description'},
],
// 界面控制
queryParamVisible,
hideQueryParam,
showQueryParam,
};
},
};
</script>

View File

@@ -0,0 +1,227 @@
<template>
<div v-if="result.data" style="margin-bottom: 30px;">
<div v-if="result.data.data || result.data.status === 200" style="margin-bottom: 30px;">
<a-tabs v-model:activeKey="activePage" @tab-click="" style="padding: 5px 10px 0;">
<a-tab-pane tab="Body" key="body" forceRender>
<div style="margin-bottom: 10px;">
<a-radio-group v-model:value="bodyShowType" @change="bodyShowTypeChange" size="small">
<a-radio-button value="format">格式化</a-radio-button>
<a-radio-button value="row">原始值</a-radio-button>
<a-radio-button value="preview">预览</a-radio-button>
</a-radio-group>
<a-select v-if="bodyShowType === 'format'" v-model:value="bodyShowFormatType" size="small" style="margin-left: 10px;width: 100px;">
<a-select-option value="json">JSON</a-select-option>
<a-select-option value="html">HTML</a-select-option>
<a-select-option value="xml">XML</a-select-option>
<a-select-option value="javascript">JavaScript</a-select-option>
<a-select-option value="text">TEXT</a-select-option>
</a-select>
</div>
<ace-editor v-if="bodyShowType === 'format'" v-model:value="resultDataContentFormat" @init="resultDataInit" :lang="bodyShowFormatType" theme="monokai" width="100%" height="100" :options="resultDataConfig"></ace-editor>
<ace-editor v-else-if="bodyShowType === 'row'" v-model:value="resultDataContentOrigin" @init="resultDataInit" lang="text" theme="chrome" width="100%" height="100" :options="resultDataConfig"></ace-editor>
<div v-else-if="bodyShowType === 'preview'">
<template v-if="bodyShowFormatPreview === 'html'">
<iframe ref="previewHtmlRef" width="100%" height="570px" style="border: 0;"></iframe>
</template>
<template v-else>{{resultDataContentOrigin}}</template>
</div>
</a-tab-pane>
<a-tab-pane tab="Headers" key="headers" forceRender>
<a-table :dataSource="resultHeaders"
:columns="resultHeadersColumns" size="small"
:pagination="false"
:scroll="{ y: '300px' }">
</a-table>
</a-tab-pane>
<a-tab-pane tab="Cookies" key="cookies" forceRender>
<a-table :dataSource="resultCookies"
:columns="resultCookiesColumns" size="small"
:pagination="false"
:scroll="{ y: '300px' }">
</a-table>
</a-tab-pane>
<template #rightExtra>
<span class="status-info-box">
状态码<span>{{resultData.status||'200'}}</span>
<a-divider type="vertical" />
耗时<span>{{unitConvert.formatSeconds(resultData.useTime||0)}}</span>
<a-divider type="vertical" />
大小<span>{{unitConvert.formatFileSize(resultData.contentLength||0)}}</span>
</span>
</template>
</a-tabs>
</div>
<div v-else>
<a-tabs style="padding: 5px 10px 0;">
<a-tab-pane tab="请求失败" key="body" forceRender>
<div style="color: #f00;">{{result.data.errorMsg}}</div>
</a-tab-pane>
<template #rightExtra>
<span class="status-info-box">
耗时<span>{{unitConvert.formatSeconds(resultData.useTime||0)}}</span>
</span>
</template>
</a-tabs>
</div>
</div>
<div v-else-if="loading" style="margin-top: 20px;">
<a-spin tip="请求执行中...">
<a-skeleton />
</a-spin>
</div>
<div v-else style="margin-top: 20px;color: #aaa;">
<a-empty description="点击 ‘发送请求’ 获取请求结果" />
</div>
</template>
<script>
import {toRefs, ref, reactive, onMounted, watch} from 'vue';
import {useRouter, useRoute} from "vue-router";
import {useStore} from 'vuex';
import {message} from 'ant-design-vue';
import {markdownIt} from 'mavon-editor'
import xmlFormatter from 'xml-formatter'
import ParamTable from '../../../components/params/ParamTable.vue'
import ParamBody from '../../../components/params/ParamBody.vue'
import {CloseOutlined} from '@ant-design/icons-vue';
import 'mavon-editor/dist/markdown/github-markdown.min.css'
import 'mavon-editor/dist/css/index.css'
import {zyplayerApi} from "../../../api";
import aceEditor from "../../../assets/ace-editor";
import unitConvert from "../../../assets/utils/unitConvert.js";
export default {
props: {
result: {
type: Object,
required: true
},
loading: {
type: Boolean,
required: true
},
},
components: {
CloseOutlined, ParamTable, ParamBody, aceEditor
},
setup(props) {
const { result } = toRefs(props);
let activePage = ref('body');
let bodyShowType = ref('format');
// 格式化展示的类型,用户可以修改
let bodyShowFormatType = ref('json');
// 预览格式依据返回值的content-type得出不可修改
let bodyShowFormatPreview = ref('');
let resultHeaders = ref([]);
let resultCookies = ref([]);
let resultDataContentOrigin = ref('');
let resultDataContentFormat = ref('');
let resultData = ref({});
let previewHtmlRef = ref();
const bodyShowTypeChange = () => {
if (bodyShowType.value === 'preview') {
setTimeout(() => {
if (previewHtmlRef.value) {
previewHtmlRef.value.contentDocument.write(resultDataContentOrigin.value);
}
}, 0);
}
}
const initData = () => {
resultDataContentOrigin.value = '';
resultDataContentFormat.value = '';
if (props.result.data) {
resultData.value = props.result.data;
if (props.result.data.headers) {
resultHeaders.value = props.result.data.headers;
// 依据返回值header判断类型
let contentType = resultHeaders.value.find(item => item.name === 'Content-Type');
if (contentType && contentType.value) {
if (contentType.value.indexOf('text/html') >= 0) {
bodyShowFormatType.value = 'html';
} else if (contentType.value.indexOf('text/plain') >= 0) {
bodyShowFormatType.value = 'text';
} else if (contentType.value.indexOf('application/json') >= 0) {
bodyShowFormatType.value = 'json';
} else if (contentType.value.indexOf('application/xml') >= 0 || contentType.value.indexOf('text/xml') >= 0) {
bodyShowFormatType.value = 'xml';
} else if (contentType.value.indexOf('application/javascript') >= 0) {
bodyShowFormatType.value = 'javascript';
}
bodyShowFormatPreview.value = bodyShowFormatType.value;
}
}
if (props.result.data.cookies) {
resultCookies.value = props.result.data.cookies;
}
if (props.result.data.data || props.result.data.status === 200) {
resultDataContentFormat.value = props.result.data.data;
resultDataContentOrigin.value = props.result.data.data;
try {
if (bodyShowFormatType.value === 'xml') {
resultDataContentFormat.value = xmlFormatter(resultDataContentOrigin.value);
} else if (bodyShowFormatType.value === 'json') {
resultDataContentFormat.value = JSON.stringify(JSON.parse(resultDataContentOrigin.value), null, 4);
} else if (bodyShowFormatType.value === 'javascript') {
// TODO 暂未测试
resultDataContentFormat.value = JSON.stringify(resultDataContentOrigin.value, null, 4);
}
} catch (e) {
resultDataContentFormat.value = props.result.data.data;
}
} else {
let errorSuffix = '\n// 请求失败,以下为封装的返回值对象,仅供参考\n\n';
resultDataContentOrigin.value = errorSuffix + JSON.stringify(props.result.data);
resultDataContentFormat.value = errorSuffix + JSON.stringify(props.result.data, null, 4);
}
bodyShowTypeChange();
}
};
initData();
watch(result, () => initData());
// 编辑器
const resultDataInit = editor => {
editor.setFontSize(16);
}
return {
activePage,
bodyShowType,
bodyShowTypeChange,
unitConvert,
bodyShowFormatType,
bodyShowFormatPreview,
previewHtmlRef,
resultData,
resultHeaders,
resultCookies,
resultHeadersColumns: [
{title: 'KEY', dataIndex: 'name'},
{title: 'VALUE', dataIndex: 'value'},
],
resultCookiesColumns: [
{title: 'KEY', dataIndex: 'name'},
{title: 'VALUE', dataIndex: 'value'},
],
// 编辑器
resultDataInit,
resultDataContentOrigin,
resultDataContentFormat,
resultDataConfig: {
wrap: true,
readOnly: true,
autoScrollEditorIntoView: true,
enableBasicAutocompletion: true,
enableSnippets: true,
enableLiveAutocompletion: true,
minLines: 30,
maxLines: 30,
},
};
},
};
</script>
<style>
.status-info-box{color: #888;}
.status-info-box span{color: #00aa00;}
.status-info-box span:last-child{margin-right: 0;}
</style>