修复bug

This commit is contained in:
梁泽军 2025-03-21 17:44:45 +08:00
parent 89c23cae2c
commit 538de6d717
13 changed files with 510 additions and 419 deletions

BIN
favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

View File

@ -1,7 +1,9 @@
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en"> <html lang="en">
<head> <head>
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<link rel="icon" href="favicon.ico" type="image/x-icon">
<script> <script>
var coverSupport = 'CSS' in window && typeof CSS.supports === 'function' && (CSS.supports('top: env(a)') || var coverSupport = 'CSS' in window && typeof CSS.supports === 'function' && (CSS.supports('top: env(a)') ||
CSS.supports('top: constant(a)')) CSS.supports('top: constant(a)'))
@ -10,12 +12,13 @@
(coverSupport ? ', viewport-fit=cover' : '') + '" />') (coverSupport ? ', viewport-fit=cover' : '') + '" />')
</script> </script>
<title></title> <title></title>
<!--preload-links--> <!--preload-links-->
<!--app-context--> <!--app-context-->
</head> </head>
<body> <body>
<div id="app"><!--app-html--></div> <div id="app"><!--app-html--></div>
<script type="module" src="/src/main.ts"></script> <script type="module" src="/src/main.ts"></script>
</body> </body>
</html> </html>

View File

@ -78,7 +78,7 @@ const setLocalStorage = async () => {
return return
} }
} else { } else {
const obj = { expire: "", value: cookiesToken } const obj = { expire: "604800", value: cookiesToken }
localStorage.setItem("app_token", JSON.stringify(obj)); localStorage.setItem("app_token", JSON.stringify(obj));
} }

View File

@ -14,7 +14,8 @@
<u-input class="flex-1" v-model="formData.mobile" :border="false" placeholder="请输入手机号码" /> <u-input class="flex-1" v-model="formData.mobile" :border="false" placeholder="请输入手机号码" />
</u-form-item> </u-form-item>
<u-form-item label="邮箱" borderBottom> <u-form-item label="邮箱" borderBottom>
<u-input class="flex-1" v-model="formData.email" :border="false" placeholder="请输入邮箱账号" /> <u-input class="flex-1" v-model="formData.email" :disabled="true" :border="false"
placeholder="请输入邮箱账号" />
</u-form-item> </u-form-item>
<u-form-item label="验证码" borderBottom> <u-form-item label="验证码" borderBottom>
<u-input class="flex-1" v-model="formData.code" placeholder="请输入验证码" :border="false" /> <u-input class="flex-1" v-model="formData.code" placeholder="请输入验证码" :border="false" />
@ -56,6 +57,15 @@ import { SMSEnum } from '@/enums/appEnums'
import { useAppStore } from '@/stores/app' import { useAppStore } from '@/stores/app'
import { reactive, ref, shallowRef, computed } from 'vue' import { reactive, ref, shallowRef, computed } from 'vue'
import { onLoad } from '@dcloudio/uni-app' import { onLoad } from '@dcloudio/uni-app'
import { useUserStore } from '@/stores/user'
const userStore = useUserStore()
const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
console.log('userStore', userInfo);
enum ForgotPwdSceneEnum { enum ForgotPwdSceneEnum {
MOBILE = 2, MOBILE = 2,
@ -89,7 +99,7 @@ const uCodeRef = shallowRef()
const codeTips = ref('') const codeTips = ref('')
const formData = reactive({ const formData = reactive({
mobile: '', mobile: '',
email: '', email: userInfo.email || '',
code: '', code: '',
scene: 3, scene: 3,
password: '', password: '',
@ -100,7 +110,7 @@ const isValidMobile = computed(() => uni.$u.test.mobile(formData.mobile))
const isValidMailBox = computed(() => uni.$u.test.email(formData.email)) const isValidMailBox = computed(() => uni.$u.test.email(formData.email))
const isMobile = computed(() => formData.scene == ForgotPwdSceneEnum.MOBILE) const isMobile = computed(() => formData.scene == ForgotPwdSceneEnum.MOBILE)
const isMailbox = computed(() => formData.scene == ForgotPwdSceneEnum.MAILBOX) const isMailbox = computed(() => formData.scene == ForgotPwdSceneEnum.MAILBOX)
console.log('isMailbox', isMailbox.value);
const codeChange = (text: string) => { const codeChange = (text: string) => {
codeTips.value = text codeTips.value = text

View File

@ -8,43 +8,22 @@
<view class="flex-1 min-h-0"> <view class="flex-1 min-h-0">
<scroll-view scroll-y class="h-full"> <scroll-view scroll-y class="h-full">
<view class="py-[14rpx] px-[30rpx]"> <view class="py-[14rpx] px-[30rpx]">
<u-search <u-search v-model="keyword" placeholder="请输入关键词搜索" height="72" bg-color="#fff" :show-action="false"
v-model="keyword" @search="getData()" />
placeholder="请输入关键词搜索"
height="72"
bg-color="#fff"
:show-action="false"
@search="getData()"
/>
</view> </view>
<view class="px-[30rpx]"> <view class="px-[30rpx]">
<template v-for="category in data" :key="category.id"> <!-- <template v-for="category in data" :key="category.id">
<view <view class="py-[25rpx]" v-if="!(category.modelsList.length == 0 && category.name == '我的收藏')">
class="py-[25rpx]"
v-if="!(category.modelsList.length == 0 && category.name == '我的收藏')"
>
<text class="font-medium text-lg">{{ category.name }}</text> <text class="font-medium text-lg">{{ category.name }}</text>
</view> </view>
<view class="flex flex-wrap mx-[-10rpx] rounded-[14rpx]"> <view class="flex flex-wrap mx-[-10rpx] rounded-[14rpx]">
<view <view class="w-1/2 px-[10rpx] mb-[20rpx]" v-for="item in category.modelsList"
class="w-1/2 px-[10rpx] mb-[20rpx]" :key="item.id">
v-for="item in category.modelsList"
:key="item.id"
>
<view class="rounded-[16rpx] py-[24rpx] h-full w-full"> <view class="rounded-[16rpx] py-[24rpx] h-full w-full">
<router-navigate <router-navigate :to="`/packages/pages/create/create?id=${item.id}`">
:to="`/packages/pages/create/create?id=${item.id}`"
>
<view class="flex w-full"> <view class="flex w-full">
<u-image <u-image :src="item.image" width="76" height="76" class="flex-none" />
:src="item.image" <view class="ml-[14rpx] flex flex-col justify-around min-w-0">
width="76"
height="76"
class="flex-none"
/>
<view
class="ml-[14rpx] flex flex-col justify-around min-w-0"
>
<view class="font-medium text-[30rpx]"> <view class="font-medium text-[30rpx]">
{{ item.name }} {{ item.name }}
</view> </view>
@ -57,7 +36,31 @@
</view> </view>
</view> </view>
</view> </view>
</template> </template> -->
<u-collapse v-for="(models, index) in data" :key="index">
<u-collapse-item :title="models.name" class="" :open="true" v-if="models.modelsList.length > 0">
<view class="flex flex-wrap ">
<view class="w-1/2 " v-for="item in models.modelsList" :key="item.id">
<view class="rounded-[16rpx] py-[24rpx]">
<router-navigate :to="`/packages/pages/create/create?id=${item.id}`">
<view class="flex w-full" :style="{ 'color': '#333' }">
<u-image :src="item.image" width="76" height="76" class="flex-none" />
<view class="ml-[14rpx] flex flex-col justify-around min-w-0">
<view class="font-medium text-[30rpx]">
{{ item.name }}
</view>
<view class="text-[24rpx] text-[#666666] truncate">
{{ item.tips }}
</view>
</view>
</view>
</router-navigate>
</view>
</view>
</view>
</u-collapse-item>
</u-collapse>
</view> </view>
</scroll-view> </scroll-view>
</view> </view>

View File

@ -60,7 +60,7 @@ const initChart = () => {
name: '部门使用次数', name: '部门使用次数',
type: 'pie', type: 'pie',
radius: ['40%', '70%'], radius: ['40%', '70%'],
avoidLabelOverlap: false, // avoidLabelOverlap: false,
top: '20%', top: '20%',
itemStyle: { itemStyle: {
borderRadius: 10 borderRadius: 10
@ -70,10 +70,10 @@ const initChart = () => {
position: 'center' position: 'center'
}, },
emphasis: { emphasis: {
label: { itemStyle: {
show: true, shadowBlur: 10,
fontSize: 40, shadowOffsetX: 0,
fontWeight: 'bold' shadowColor: 'rgba(0, 0, 0, 0.5)'
} }
}, },
labelLine: { labelLine: {

View File

@ -49,7 +49,11 @@ import Tabs from '@/packages/components/tabs/tabs.vue'
import Tab from '@/packages/components/tab/tab.vue' import Tab from '@/packages/components/tab/tab.vue'
import uCalendar from '@/uni_modules/vk-uview-ui/components/u-calendar/u-calendar.vue' import uCalendar from '@/uni_modules/vk-uview-ui/components/u-calendar/u-calendar.vue'
import uField from '@/uni_modules/vk-uview-ui/components/u-field/u-field.vue' import uField from '@/uni_modules/vk-uview-ui/components/u-field/u-field.vue'
import { useUserStore } from '@/stores/user'
import { useRouter } from 'uniapp-router-next'
const userStore = useUserStore()
const router = useRouter()
// 7 // 7
@ -109,6 +113,11 @@ const getData = async () => {
status.value = PageStatusEnum.NORMAL status.value = PageStatusEnum.NORMAL
} catch (error) { } catch (error) {
console.log('error', error);
if (!userStore.isLogin) {
uni.$u.toast('未登录')
router.navigateTo({ path: '/pages/login/login' })
}
status.value = PageStatusEnum.ERROR status.value = PageStatusEnum.ERROR
} }
} }

View File

@ -40,5 +40,8 @@ export const useAppStore = defineStore({
const data = await getConfig({ type: 1 }); const data = await getConfig({ type: 1 });
this.config = data; this.config = data;
}, },
setToken(token: string) {
this.config.token = token;
},
}, },
}); });

View File

@ -28,16 +28,18 @@ export const useUserStore = defineStore({
token: this.token, token: this.token,
}); });
this.userInfo = data; this.userInfo = data;
localStorage.setItem("userInfo", JSON.stringify(data));
}, },
login(token: string) { login(token: string) {
cache.set(TOKEN_KEY, token); cache.set(TOKEN_KEY, token, "604800");
this.token = token; this.token = token;
useSharedId(); useSharedId();
}, },
logout() { logout() {
this.token = ""; this.token = "";
this.userInfo = {}; this.userInfo = {};
cache.remove(TOKEN_KEY); // cache.remove(TOKEN_KEY);
}, },
}, },
}); });

View File

@ -11,7 +11,7 @@ const isWechatWork = () => {
export function getToken() { export function getToken() {
if (isWechatWork()) { if (isWechatWork()) {
const token = Cookies.get("token"); const token = Cookies.get("token");
const obj = { expire: "", value: token }; const obj = { expire: "604800", value: token };
localStorage.setItem("app_token", JSON.stringify(obj)); localStorage.setItem("app_token", JSON.stringify(obj));
return token || ""; return token || "";
} else { } else {

View File

@ -1,50 +1,51 @@
const cache = { const cache = {
key: 'app_', key: "app_",
//设置缓存(expire为缓存时效) //设置缓存(expire为缓存时效)
set(key: string, value: any, expire?: string) { set(key: string, value: any, expire?: string) {
key = this.getKey(key) key = this.getKey(key);
let data: any = { let data: any = {
expire: expire ? this.time() + expire : '', expire: expire ? this.time() + expire : "",
value value,
} };
if (typeof data === 'object') { if (typeof data === "object") {
data = JSON.stringify(data) data = JSON.stringify(data);
} }
try { try {
uni.setStorageSync(key, data) uni.setStorageSync(key, data);
} catch (e) { } catch (e) {
return undefined return undefined;
} }
}, },
get(key: string) { get(key: string) {
key = this.getKey(key) key = this.getKey(key);
try { try {
const data = uni.getStorageSync(key) const data = uni.getStorageSync(key);
if (!data) { if (!data) {
return undefined return undefined;
} }
const { value, expire } = JSON.parse(data) const { value, expire } = JSON.parse(data);
if (expire && expire < this.time()) { if (expire && expire < this.time()) {
uni.removeStorageSync(key) uni.removeStorageSync(key);
return undefined return undefined;
} }
return value return value;
} catch (e) { } catch (e) {
return undefined return undefined;
} }
}, },
//获取当前时间 //获取当前时间
time() { time() {
return Math.round(new Date().getTime() / 1000) return Math.round(new Date().getTime() / 1000);
}, },
remove(key: string) { remove(key: string) {
key = this.getKey(key) key = this.getKey(key);
uni.removeStorageSync(key) uni.removeStorageSync(key);
}, },
getKey(key: string) { getKey(key: string) {
return this.key + key return this.key + key;
} },
} };
export default cache export default cache;

View File

@ -1,348 +1,406 @@
import { merge } from 'lodash-es' import { merge } from "lodash-es";
import { isFunction } from '@vue/shared' import { isFunction } from "@vue/shared";
import { import {
HttpRequestOptions, HttpRequestOptions,
RequestConfig, RequestConfig,
RequestEventStreamConfig, RequestEventStreamConfig,
RequestOptions, RequestOptions,
UploadFileOption UploadFileOption,
} from './type' } from "./type";
import { RequestErrMsgEnum, RequestMethodsEnum } from '@/enums/requestEnums' import { RequestErrMsgEnum, RequestMethodsEnum } from "@/enums/requestEnums";
import requestCancel from './cancel' import requestCancel from "./cancel";
import { objectToQuery } from '../util' import { objectToQuery } from "../util";
import { isObject } from 'mathjs' import { isObject } from "mathjs";
import {Base64} from 'js-base64' import { Base64 } from "js-base64";
import { parse } from 'jsonc-parser' import { parse } from "jsonc-parser";
/** /**
* @description utf-8 * @description utf-8
*/ */
function decodeUTF8(arr: Uint8Array) { function decodeUTF8(arr: Uint8Array) {
let str = '' let str = "";
for (let i = 0; i < arr.length; i++) { for (let i = 0; i < arr.length; i++) {
str += String.fromCharCode(arr[i]) str += String.fromCharCode(arr[i]);
} }
return decodeURIComponent(escape(str)) return decodeURIComponent(escape(str));
} }
function isStreamResponse(header?: any) { function isStreamResponse(header?: any) {
const contentType = header?.['Content-Type'] || header?.['content-type'] || header.get('content-type')! const contentType =
if (typeof contentType !== 'string') return false header?.["Content-Type"] ||
return contentType.includes('text/event-stream') header?.["content-type"] ||
header.get("content-type")!;
if (typeof contentType !== "string") return false;
return contentType.includes("text/event-stream");
} }
export default class HttpRequest { export default class HttpRequest {
private readonly options: HttpRequestOptions private readonly options: HttpRequestOptions;
constructor(options: HttpRequestOptions) { constructor(options: HttpRequestOptions) {
this.options = options this.options = options;
} }
/** /**
* @description * @description
*/ */
retryRequest(options: RequestOptions, config: RequestConfig) { retryRequest(options: RequestOptions, config: RequestConfig) {
const { retryCount, retryTimeout } = config const { retryCount, retryTimeout } = config;
if (!retryCount || options.method?.toUpperCase() == RequestMethodsEnum.POST) { if (
return Promise.reject() !retryCount ||
options.method?.toUpperCase() == RequestMethodsEnum.POST
) {
return Promise.reject();
} }
uni.showLoading({ title: '加载中...' }) uni.showLoading({ title: "加载中..." });
config.hasRetryCount = config.hasRetryCount || 0 config.hasRetryCount = config.hasRetryCount || 0;
if (config.hasRetryCount >= retryCount) { if (config.hasRetryCount >= retryCount) {
return Promise.reject() return Promise.reject();
} }
config.hasRetryCount++ config.hasRetryCount++;
config.requestHooks.requestInterceptorsHook = (options) => options config.requestHooks.requestInterceptorsHook = (options) => options;
return new Promise((resolve) => setTimeout(resolve, retryTimeout)) return new Promise((resolve) => setTimeout(resolve, retryTimeout))
.then(() => this.request(options, config)) .then(() => this.request(options, config))
.finally(() => uni.hideLoading()) .finally(() => uni.hideLoading());
} }
/** /**
* @description get请求 * @description get请求
*/ */
get<T = any>(options: RequestOptions, config?: Partial<RequestConfig>): Promise<T> { get<T = any>(
return this.request({ ...options, method: RequestMethodsEnum.GET }, config) options: RequestOptions,
config?: Partial<RequestConfig>
): Promise<T> {
return this.request({ ...options, method: RequestMethodsEnum.GET }, config);
} }
/** /**
* @description post请求 * @description post请求
*/ */
post<T = any>(options: RequestOptions, config?: Partial<RequestConfig>): Promise<T> { post<T = any>(
return this.request({ ...options, method: RequestMethodsEnum.POST }, config) options: RequestOptions,
config?: Partial<RequestConfig>
): Promise<T> {
return this.request(
{ ...options, method: RequestMethodsEnum.POST },
config
);
} }
/** /**
* @description * @description
*/ */
eventStream(options: RequestOptions, config?: RequestEventStreamConfig) { eventStream(options: RequestOptions, config?: RequestEventStreamConfig) {
let mergeOptions: RequestOptions = merge({}, this.options.requestOptions, options) let mergeOptions: RequestOptions = merge(
const mergeConfig: RequestEventStreamConfig = merge({}, this.options, config) {},
const { requestInterceptorsHook, responseInterceptorsHook } = mergeConfig.requestHooks || {} this.options.requestOptions,
options
);
const mergeConfig: RequestEventStreamConfig = merge(
{},
this.options,
config
);
const { requestInterceptorsHook, responseInterceptorsHook } =
mergeConfig.requestHooks || {};
if (requestInterceptorsHook && isFunction(requestInterceptorsHook)) { if (requestInterceptorsHook && isFunction(requestInterceptorsHook)) {
mergeOptions = requestInterceptorsHook(mergeOptions, mergeConfig as RequestConfig) mergeOptions = requestInterceptorsHook(
mergeOptions,
mergeConfig as RequestConfig
);
} }
const { onmessage, onclose, onstart } = mergeConfig const { onmessage, onclose, onstart } = mergeConfig;
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
try { try {
// #ifdef H5 // #ifdef H5
const decoder = new TextDecoder() const decoder = new TextDecoder();
const abortController = new AbortController() const abortController = new AbortController();
const push = async (controller: any, reader: any) => { const push = async (controller: any, reader: any) => {
try { try {
const { value, done } = await reader.read() const { value, done } = await reader.read();
if (done) { if (done) {
controller.close() controller.close();
onclose?.() onclose?.();
} else { } else {
const tempval = Base64.decode(decoder.decode(value)) const tempval = Base64.decode(decoder.decode(value));
onmessage?.(tempval) onmessage?.(tempval);
controller.enqueue(tempval) controller.enqueue(tempval);
push(controller, reader) push(controller, reader);
} }
} catch (error) { } catch (error) {
onclose?.() onclose?.();
}
} }
};
if (mergeOptions.method!.toUpperCase() == RequestMethodsEnum.GET) { if (mergeOptions.method!.toUpperCase() == RequestMethodsEnum.GET) {
if (isObject(mergeOptions.data)) { if (isObject(mergeOptions.data)) {
mergeOptions.data = objectToQuery(mergeOptions.data as Record<string, any>) mergeOptions.data = objectToQuery(
mergeOptions.data as Record<string, any>
);
} }
mergeOptions.url = `${mergeOptions.url}?${mergeOptions.data}` mergeOptions.url = `${mergeOptions.url}?${mergeOptions.data}`;
} }
let body = undefined let body = undefined;
if (mergeOptions.method!.toUpperCase() == RequestMethodsEnum.POST) { if (mergeOptions.method!.toUpperCase() == RequestMethodsEnum.POST) {
body = isObject(mergeOptions.data) body = isObject(mergeOptions.data)
? JSON.stringify(mergeOptions.data) ? JSON.stringify(mergeOptions.data)
: (mergeOptions.data as string) : (mergeOptions.data as string);
} }
fetch(mergeOptions.url, { fetch(mergeOptions.url, {
...mergeOptions, ...mergeOptions,
signal: abortController.signal, signal: abortController.signal,
body, body,
headers: { headers: {
'content-type': 'application/json; charset=utf-8', "content-type": "application/json; charset=utf-8",
...mergeOptions.header, ...mergeOptions.header,
Accept: 'text/event-stream' Accept: "text/event-stream",
} },
}) })
.then(async (response) => { .then(async (response) => {
if (response.status == 200) { if (response.status == 200) {
if (isStreamResponse(response.headers)) { if (isStreamResponse(response.headers)) {
const reader = response.body!.getReader() const reader = response.body!.getReader();
onstart?.(abortController) onstart?.(abortController);
new ReadableStream({ new ReadableStream({
start(controller) { start(controller) {
push(controller, reader) push(controller, reader);
} },
}) });
} else { } else {
//@ts-ignore //@ts-ignore
response.data = await response.json() response.data = await response.json();
return response return response;
} }
} else { } else {
reject(response.statusText) reject(response.statusText);
} }
}) })
.then(async (response: any) => { .then(async (response: any) => {
if (!response) { if (!response) {
resolve(response) resolve(response);
return return;
} }
if (responseInterceptorsHook && isFunction(responseInterceptorsHook)) { if (
responseInterceptorsHook &&
isFunction(responseInterceptorsHook)
) {
try { try {
response = await responseInterceptorsHook( response = await responseInterceptorsHook(
response, response,
mergeConfig as RequestConfig, mergeConfig as RequestConfig,
mergeOptions mergeOptions
) );
resolve(response) resolve(response);
} catch (error) { } catch (error) {
reject(error) reject(error);
} }
return return;
} }
resolve(response) resolve(response);
}) })
.catch((error) => { .catch((error) => {
reject(error) reject(error);
}) });
// #endif // #endif
// #ifdef MP-WEIXIN // #ifdef MP-WEIXIN
let header: Record<string, any> = {} let header: Record<string, any> = {};
const requestTask = uni.request({ const requestTask = uni.request({
...mergeOptions, ...mergeOptions,
enableChunked: true, enableChunked: true,
responseType: 'arraybuffer', responseType: "arraybuffer",
async success(response) { async success(response) {
if (response.statusCode !== 200) { if (response.statusCode !== 200) {
reject(response) reject(response);
return return;
} }
resolve(response) resolve(response);
}, },
fail(error) { fail(error) {
reject(error) reject(error);
}, },
complete() { complete() {
onclose?.() onclose?.();
} },
}) });
onstart?.(requestTask) onstart?.(requestTask);
//@ts-ignore //@ts-ignore
requestTask.onHeadersReceived((response) => { requestTask.onHeadersReceived((response) => {
header = response.header header = response.header;
}) });
//@ts-ignore //@ts-ignore
requestTask.onChunkReceived(async (response) => { requestTask.onChunkReceived(async (response) => {
const arrayBuffer = response.data const arrayBuffer = response.data;
const uint8Array = new Uint8Array(arrayBuffer) const uint8Array = new Uint8Array(arrayBuffer);
const base64str = decodeUTF8(uint8Array) const base64str = decodeUTF8(uint8Array);
const str = Base64.decode(base64str); const str = Base64.decode(base64str);
if (isStreamResponse(header)) { if (isStreamResponse(header)) {
console.log(str) console.log(str);
onmessage?.(str) onmessage?.(str);
} else { } else {
const data = parse(str) const data = parse(str);
if (responseInterceptorsHook && isFunction(responseInterceptorsHook)) { if (
responseInterceptorsHook &&
isFunction(responseInterceptorsHook)
) {
try { try {
const response = await responseInterceptorsHook( const response = await responseInterceptorsHook(
{ data, statusCode: 200 }, { data, statusCode: 200 },
mergeConfig as RequestConfig, mergeConfig as RequestConfig,
mergeOptions mergeOptions
) );
resolve(response) resolve(response);
} catch (error) { } catch (error) {
reject(error) reject(error);
} }
return return;
} }
} }
}) });
// #endif // #endif
} catch (e) { } catch (e) {
reject() reject();
} }
}) });
} }
/** /**
* @description * @description
*/ */
uploadFile(options: UploadFileOption, config?: Partial<RequestConfig>) { uploadFile(options: UploadFileOption, config?: Partial<RequestConfig>) {
let mergeOptions: RequestOptions = merge({}, this.options.requestOptions, options) let mergeOptions: RequestOptions = merge(
const mergeConfig: RequestConfig = merge({}, this.options, config) {},
const { requestInterceptorsHook, responseInterceptorsHook, responseInterceptorsCatchHook } = this.options.requestOptions,
mergeConfig.requestHooks || {} options
);
const mergeConfig: RequestConfig = merge({}, this.options, config);
const {
requestInterceptorsHook,
responseInterceptorsHook,
responseInterceptorsCatchHook,
} = mergeConfig.requestHooks || {};
if (requestInterceptorsHook && isFunction(requestInterceptorsHook)) { if (requestInterceptorsHook && isFunction(requestInterceptorsHook)) {
mergeOptions = requestInterceptorsHook(mergeOptions, mergeConfig) mergeOptions = requestInterceptorsHook(mergeOptions, mergeConfig);
} }
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const task = uni.uploadFile({ const task = uni.uploadFile({
...mergeOptions, ...mergeOptions,
header: { header: {
...mergeOptions.header ...mergeOptions.header,
}, },
async success(response) { async success(response) {
if (response.statusCode == 200) { if (response.statusCode == 200) {
response.data = parse(response.data) response.data = parse(response.data);
if (responseInterceptorsHook && isFunction(responseInterceptorsHook)) { if (
responseInterceptorsHook &&
isFunction(responseInterceptorsHook)
) {
try { try {
response = await responseInterceptorsHook( response = await responseInterceptorsHook(
response, response,
mergeConfig, mergeConfig,
mergeOptions mergeOptions
) );
resolve(response) resolve(response);
} catch (error) { } catch (error) {
reject(error) reject(error);
} }
return return;
} }
resolve(response) resolve(response);
} else { } else {
reject(response.errMsg) reject(response.errMsg);
} }
}, },
fail(err) { fail(err) {
if (err.errMsg == RequestErrMsgEnum.ABORT) { if (err.errMsg == RequestErrMsgEnum.ABORT) {
return return;
} }
if ( if (
responseInterceptorsCatchHook && responseInterceptorsCatchHook &&
isFunction(responseInterceptorsCatchHook) isFunction(responseInterceptorsCatchHook)
) { ) {
reject(responseInterceptorsCatchHook(mergeOptions, err)) reject(responseInterceptorsCatchHook(mergeOptions, err));
return return;
} }
reject(err) reject(err);
} },
}) });
task.onProgressUpdate(({ progress }) => { task.onProgressUpdate(({ progress }) => {
mergeConfig.onProgress?.(progress) mergeConfig.onProgress?.(progress);
}) });
}) });
} }
/** /**
* @description * @description
*/ */
async request(options: RequestOptions, config?: Partial<RequestConfig>): Promise<any> { async request(
let mergeOptions: RequestOptions = merge({}, this.options.requestOptions, options) options: RequestOptions,
const mergeConfig: RequestConfig = merge({}, this.options, config) config?: Partial<RequestConfig>
const { requestInterceptorsHook, responseInterceptorsHook, responseInterceptorsCatchHook } = ): Promise<any> {
mergeConfig.requestHooks || {} let mergeOptions: RequestOptions = merge(
{},
this.options.requestOptions,
options
);
const mergeConfig: RequestConfig = merge({}, this.options, config);
const {
requestInterceptorsHook,
responseInterceptorsHook,
responseInterceptorsCatchHook,
} = mergeConfig.requestHooks || {};
if (requestInterceptorsHook && isFunction(requestInterceptorsHook)) { if (requestInterceptorsHook && isFunction(requestInterceptorsHook)) {
mergeOptions = requestInterceptorsHook(mergeOptions, mergeConfig) mergeOptions = requestInterceptorsHook(mergeOptions, mergeConfig);
} }
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const requestTask = uni.request({ const requestTask = uni.request({
...mergeOptions, ...mergeOptions,
async success(response) { async success(response) {
if (response.statusCode !== 200) { if (response.statusCode !== 200) {
return reject() return reject();
} }
if (responseInterceptorsHook && isFunction(responseInterceptorsHook)) { if (
responseInterceptorsHook &&
isFunction(responseInterceptorsHook)
) {
try { try {
response = await responseInterceptorsHook( response = await responseInterceptorsHook(
response, response,
mergeConfig, mergeConfig,
mergeOptions mergeOptions
) );
resolve(response) resolve(response);
} catch (error) { } catch (error) {
reject(error) reject(error);
} }
return return;
} }
resolve(response) resolve(response);
}, },
fail: async (err) => { fail: async (err) => {
if (err.errMsg == RequestErrMsgEnum.TIMEOUT) { if (err.errMsg == RequestErrMsgEnum.TIMEOUT) {
this.retryRequest(mergeOptions, mergeConfig) this.retryRequest(mergeOptions, mergeConfig)
.then((res) => resolve(res)) .then((res) => resolve(res))
.catch((err) => reject(err)) .catch((err) => reject(err));
return return;
} }
if (err.errMsg == RequestErrMsgEnum.ABORT) { if (err.errMsg == RequestErrMsgEnum.ABORT) {
return return;
} }
if ( if (
responseInterceptorsCatchHook && responseInterceptorsCatchHook &&
isFunction(responseInterceptorsCatchHook) isFunction(responseInterceptorsCatchHook)
) { ) {
reject(await responseInterceptorsCatchHook(mergeOptions, err)) reject(await responseInterceptorsCatchHook(mergeOptions, err));
return return;
} }
reject(err) reject(err);
}, },
complete(err) { complete(err) {
if (err.errMsg !== RequestErrMsgEnum.ABORT) { if (err.errMsg !== RequestErrMsgEnum.ABORT) {
requestCancel.remove(options.url) requestCancel.remove(options.url);
} }
} },
}) });
const { ignoreCancel } = mergeConfig const { ignoreCancel } = mergeConfig;
!ignoreCancel && requestCancel.add(options.url, requestTask) !ignoreCancel && requestCancel.add(options.url, requestTask);
}) });
} }
} }

View File

@ -31,6 +31,8 @@ export default defineConfig(({ mode }) => {
return { return {
// base: "https://cdn.xglpa.com/ai-agent-m/", // base: "https://cdn.xglpa.com/ai-agent-m/",
base: mode === "production" ? "https://cdn.xglpa.com/ai-agent-m/" : "./",
plugins: [ plugins: [
uni(), uni(),
uniRouter({ uniRouter({