修复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 {
uni.setStorageSync(key, data)
} catch (e) {
return undefined
}
},
get(key: string) {
key = this.getKey(key)
try {
const data = uni.getStorageSync(key)
if (!data) {
return undefined
}
const { value, expire } = JSON.parse(data)
if (expire && expire < this.time()) {
uni.removeStorageSync(key)
return undefined
}
return value
} catch (e) {
return undefined
}
},
//获取当前时间
time() {
return Math.round(new Date().getTime() / 1000)
},
remove(key: string) {
key = this.getKey(key)
uni.removeStorageSync(key)
},
getKey(key: string) {
return this.key + key
} }
} try {
uni.setStorageSync(key, data);
} catch (e) {
return undefined;
}
},
get(key: string) {
key = this.getKey(key);
try {
const data = uni.getStorageSync(key);
export default cache if (!data) {
return undefined;
}
const { value, expire } = JSON.parse(data);
if (expire && expire < this.time()) {
uni.removeStorageSync(key);
return undefined;
}
return value;
} catch (e) {
return undefined;
}
},
//获取当前时间
time() {
return Math.round(new Date().getTime() / 1000);
},
remove(key: string) {
key = this.getKey(key);
uni.removeStorageSync(key);
},
getKey(key: string) {
return this.key + key;
},
};
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
*/
retryRequest(options: RequestOptions, config: RequestConfig) {
const { retryCount, retryTimeout } = config;
if (
!retryCount ||
options.method?.toUpperCase() == RequestMethodsEnum.POST
) {
return Promise.reject();
} }
/** uni.showLoading({ title: "加载中..." });
* @description config.hasRetryCount = config.hasRetryCount || 0;
*/ if (config.hasRetryCount >= retryCount) {
retryRequest(options: RequestOptions, config: RequestConfig) { return Promise.reject();
const { retryCount, retryTimeout } = config
if (!retryCount || options.method?.toUpperCase() == RequestMethodsEnum.POST) {
return Promise.reject()
}
uni.showLoading({ title: '加载中...' })
config.hasRetryCount = config.hasRetryCount || 0
if (config.hasRetryCount >= retryCount) {
return Promise.reject()
}
config.hasRetryCount++
config.requestHooks.requestInterceptorsHook = (options) => options
return new Promise((resolve) => setTimeout(resolve, retryTimeout))
.then(() => this.request(options, config))
.finally(() => uni.hideLoading())
} }
/** config.hasRetryCount++;
* @description get请求 config.requestHooks.requestInterceptorsHook = (options) => options;
*/ return new Promise((resolve) => setTimeout(resolve, retryTimeout))
get<T = any>(options: RequestOptions, config?: Partial<RequestConfig>): Promise<T> { .then(() => this.request(options, config))
return this.request({ ...options, method: RequestMethodsEnum.GET }, config) .finally(() => uni.hideLoading());
}
/**
* @description get请求
*/
get<T = any>(
options: RequestOptions,
config?: Partial<RequestConfig>
): Promise<T> {
return this.request({ ...options, method: RequestMethodsEnum.GET }, config);
}
/**
* @description post请求
*/
post<T = any>(
options: RequestOptions,
config?: Partial<RequestConfig>
): Promise<T> {
return this.request(
{ ...options, method: RequestMethodsEnum.POST },
config
);
}
/**
* @description
*/
eventStream(options: RequestOptions, config?: RequestEventStreamConfig) {
let mergeOptions: RequestOptions = merge(
{},
this.options.requestOptions,
options
);
const mergeConfig: RequestEventStreamConfig = merge(
{},
this.options,
config
);
const { requestInterceptorsHook, responseInterceptorsHook } =
mergeConfig.requestHooks || {};
if (requestInterceptorsHook && isFunction(requestInterceptorsHook)) {
mergeOptions = requestInterceptorsHook(
mergeOptions,
mergeConfig as RequestConfig
);
} }
/** const { onmessage, onclose, onstart } = mergeConfig;
* @description post请求 return new Promise((resolve, reject) => {
*/ try {
post<T = any>(options: RequestOptions, config?: Partial<RequestConfig>): Promise<T> { // #ifdef H5
return this.request({ ...options, method: RequestMethodsEnum.POST }, config) const decoder = new TextDecoder();
} const abortController = new AbortController();
/** const push = async (controller: any, reader: any) => {
* @description try {
*/ const { value, done } = await reader.read();
eventStream(options: RequestOptions, config?: RequestEventStreamConfig) { if (done) {
let mergeOptions: RequestOptions = merge({}, this.options.requestOptions, options) controller.close();
const mergeConfig: RequestEventStreamConfig = merge({}, this.options, config) onclose?.();
const { requestInterceptorsHook, responseInterceptorsHook } = mergeConfig.requestHooks || {} } else {
if (requestInterceptorsHook && isFunction(requestInterceptorsHook)) { const tempval = Base64.decode(decoder.decode(value));
mergeOptions = requestInterceptorsHook(mergeOptions, mergeConfig as RequestConfig) onmessage?.(tempval);
} controller.enqueue(tempval);
push(controller, reader);
const { onmessage, onclose, onstart } = mergeConfig
return new Promise((resolve, reject) => {
try {
// #ifdef H5
const decoder = new TextDecoder()
const abortController = new AbortController()
const push = async (controller: any, reader: any) => {
try {
const { value, done } = await reader.read()
if (done) {
controller.close()
onclose?.()
} else {
const tempval = Base64.decode(decoder.decode(value))
onmessage?.(tempval)
controller.enqueue(tempval)
push(controller, reader)
}
} catch (error) {
onclose?.()
}
}
if (mergeOptions.method!.toUpperCase() == RequestMethodsEnum.GET) {
if (isObject(mergeOptions.data)) {
mergeOptions.data = objectToQuery(mergeOptions.data as Record<string, any>)
}
mergeOptions.url = `${mergeOptions.url}?${mergeOptions.data}`
}
let body = undefined
if (mergeOptions.method!.toUpperCase() == RequestMethodsEnum.POST) {
body = isObject(mergeOptions.data)
? JSON.stringify(mergeOptions.data)
: (mergeOptions.data as string)
}
fetch(mergeOptions.url, {
...mergeOptions,
signal: abortController.signal,
body,
headers: {
'content-type': 'application/json; charset=utf-8',
...mergeOptions.header,
Accept: 'text/event-stream'
}
})
.then(async (response) => {
if (response.status == 200) {
if (isStreamResponse(response.headers)) {
const reader = response.body!.getReader()
onstart?.(abortController)
new ReadableStream({
start(controller) {
push(controller, reader)
}
})
} else {
//@ts-ignore
response.data = await response.json()
return response
}
} else {
reject(response.statusText)
}
})
.then(async (response: any) => {
if (!response) {
resolve(response)
return
}
if (responseInterceptorsHook && isFunction(responseInterceptorsHook)) {
try {
response = await responseInterceptorsHook(
response,
mergeConfig as RequestConfig,
mergeOptions
)
resolve(response)
} catch (error) {
reject(error)
}
return
}
resolve(response)
})
.catch((error) => {
reject(error)
})
// #endif
// #ifdef MP-WEIXIN
let header: Record<string, any> = {}
const requestTask = uni.request({
...mergeOptions,
enableChunked: true,
responseType: 'arraybuffer',
async success(response) {
if (response.statusCode !== 200) {
reject(response)
return
}
resolve(response)
},
fail(error) {
reject(error)
},
complete() {
onclose?.()
}
})
onstart?.(requestTask)
//@ts-ignore
requestTask.onHeadersReceived((response) => {
header = response.header
})
//@ts-ignore
requestTask.onChunkReceived(async (response) => {
const arrayBuffer = response.data
const uint8Array = new Uint8Array(arrayBuffer)
const base64str = decodeUTF8(uint8Array)
const str = Base64.decode(base64str);
if (isStreamResponse(header)) {
console.log(str)
onmessage?.(str)
} else {
const data = parse(str)
if (responseInterceptorsHook && isFunction(responseInterceptorsHook)) {
try {
const response = await responseInterceptorsHook(
{ data, statusCode: 200 },
mergeConfig as RequestConfig,
mergeOptions
)
resolve(response)
} catch (error) {
reject(error)
}
return
}
}
})
// #endif
} catch (e) {
reject()
} }
}) } catch (error) {
} onclose?.();
/** }
* @description };
*/
uploadFile(options: UploadFileOption, config?: Partial<RequestConfig>) {
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)) {
mergeOptions = requestInterceptorsHook(mergeOptions, mergeConfig)
}
return new Promise((resolve, reject) => {
const task = uni.uploadFile({
...mergeOptions,
header: {
...mergeOptions.header
},
async success(response) {
if (response.statusCode == 200) {
response.data = parse(response.data)
if (responseInterceptorsHook && isFunction(responseInterceptorsHook)) {
try {
response = await responseInterceptorsHook(
response,
mergeConfig,
mergeOptions
)
resolve(response)
} catch (error) {
reject(error)
}
return
}
resolve(response) if (mergeOptions.method!.toUpperCase() == RequestMethodsEnum.GET) {
} else { if (isObject(mergeOptions.data)) {
reject(response.errMsg) mergeOptions.data = objectToQuery(
} mergeOptions.data as Record<string, any>
}, );
fail(err) { }
if (err.errMsg == RequestErrMsgEnum.ABORT) { mergeOptions.url = `${mergeOptions.url}?${mergeOptions.data}`;
return
}
if (
responseInterceptorsCatchHook &&
isFunction(responseInterceptorsCatchHook)
) {
reject(responseInterceptorsCatchHook(mergeOptions, err))
return
}
reject(err)
}
})
task.onProgressUpdate(({ progress }) => {
mergeConfig.onProgress?.(progress)
})
})
}
/**
* @description
*/
async request(options: RequestOptions, config?: Partial<RequestConfig>): Promise<any> {
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)) {
mergeOptions = requestInterceptorsHook(mergeOptions, mergeConfig)
} }
return new Promise((resolve, reject) => { let body = undefined;
const requestTask = uni.request({ if (mergeOptions.method!.toUpperCase() == RequestMethodsEnum.POST) {
...mergeOptions, body = isObject(mergeOptions.data)
async success(response) { ? JSON.stringify(mergeOptions.data)
if (response.statusCode !== 200) { : (mergeOptions.data as string);
return reject() }
} fetch(mergeOptions.url, {
if (responseInterceptorsHook && isFunction(responseInterceptorsHook)) { ...mergeOptions,
try { signal: abortController.signal,
response = await responseInterceptorsHook( body,
response, headers: {
mergeConfig, "content-type": "application/json; charset=utf-8",
mergeOptions ...mergeOptions.header,
) Accept: "text/event-stream",
resolve(response) },
} catch (error) {
reject(error)
}
return
}
resolve(response)
},
fail: async (err) => {
if (err.errMsg == RequestErrMsgEnum.TIMEOUT) {
this.retryRequest(mergeOptions, mergeConfig)
.then((res) => resolve(res))
.catch((err) => reject(err))
return
}
if (err.errMsg == RequestErrMsgEnum.ABORT) {
return
}
if (
responseInterceptorsCatchHook &&
isFunction(responseInterceptorsCatchHook)
) {
reject(await responseInterceptorsCatchHook(mergeOptions, err))
return
}
reject(err)
},
complete(err) {
if (err.errMsg !== RequestErrMsgEnum.ABORT) {
requestCancel.remove(options.url)
}
}
})
const { ignoreCancel } = mergeConfig
!ignoreCancel && requestCancel.add(options.url, requestTask)
}) })
.then(async (response) => {
if (response.status == 200) {
if (isStreamResponse(response.headers)) {
const reader = response.body!.getReader();
onstart?.(abortController);
new ReadableStream({
start(controller) {
push(controller, reader);
},
});
} else {
//@ts-ignore
response.data = await response.json();
return response;
}
} else {
reject(response.statusText);
}
})
.then(async (response: any) => {
if (!response) {
resolve(response);
return;
}
if (
responseInterceptorsHook &&
isFunction(responseInterceptorsHook)
) {
try {
response = await responseInterceptorsHook(
response,
mergeConfig as RequestConfig,
mergeOptions
);
resolve(response);
} catch (error) {
reject(error);
}
return;
}
resolve(response);
})
.catch((error) => {
reject(error);
});
// #endif
// #ifdef MP-WEIXIN
let header: Record<string, any> = {};
const requestTask = uni.request({
...mergeOptions,
enableChunked: true,
responseType: "arraybuffer",
async success(response) {
if (response.statusCode !== 200) {
reject(response);
return;
}
resolve(response);
},
fail(error) {
reject(error);
},
complete() {
onclose?.();
},
});
onstart?.(requestTask);
//@ts-ignore
requestTask.onHeadersReceived((response) => {
header = response.header;
});
//@ts-ignore
requestTask.onChunkReceived(async (response) => {
const arrayBuffer = response.data;
const uint8Array = new Uint8Array(arrayBuffer);
const base64str = decodeUTF8(uint8Array);
const str = Base64.decode(base64str);
if (isStreamResponse(header)) {
console.log(str);
onmessage?.(str);
} else {
const data = parse(str);
if (
responseInterceptorsHook &&
isFunction(responseInterceptorsHook)
) {
try {
const response = await responseInterceptorsHook(
{ data, statusCode: 200 },
mergeConfig as RequestConfig,
mergeOptions
);
resolve(response);
} catch (error) {
reject(error);
}
return;
}
}
});
// #endif
} catch (e) {
reject();
}
});
}
/**
* @description
*/
uploadFile(options: UploadFileOption, config?: Partial<RequestConfig>) {
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)) {
mergeOptions = requestInterceptorsHook(mergeOptions, mergeConfig);
} }
return new Promise((resolve, reject) => {
const task = uni.uploadFile({
...mergeOptions,
header: {
...mergeOptions.header,
},
async success(response) {
if (response.statusCode == 200) {
response.data = parse(response.data);
if (
responseInterceptorsHook &&
isFunction(responseInterceptorsHook)
) {
try {
response = await responseInterceptorsHook(
response,
mergeConfig,
mergeOptions
);
resolve(response);
} catch (error) {
reject(error);
}
return;
}
resolve(response);
} else {
reject(response.errMsg);
}
},
fail(err) {
if (err.errMsg == RequestErrMsgEnum.ABORT) {
return;
}
if (
responseInterceptorsCatchHook &&
isFunction(responseInterceptorsCatchHook)
) {
reject(responseInterceptorsCatchHook(mergeOptions, err));
return;
}
reject(err);
},
});
task.onProgressUpdate(({ progress }) => {
mergeConfig.onProgress?.(progress);
});
});
}
/**
* @description
*/
async request(
options: RequestOptions,
config?: Partial<RequestConfig>
): Promise<any> {
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)) {
mergeOptions = requestInterceptorsHook(mergeOptions, mergeConfig);
}
return new Promise((resolve, reject) => {
const requestTask = uni.request({
...mergeOptions,
async success(response) {
if (response.statusCode !== 200) {
return reject();
}
if (
responseInterceptorsHook &&
isFunction(responseInterceptorsHook)
) {
try {
response = await responseInterceptorsHook(
response,
mergeConfig,
mergeOptions
);
resolve(response);
} catch (error) {
reject(error);
}
return;
}
resolve(response);
},
fail: async (err) => {
if (err.errMsg == RequestErrMsgEnum.TIMEOUT) {
this.retryRequest(mergeOptions, mergeConfig)
.then((res) => resolve(res))
.catch((err) => reject(err));
return;
}
if (err.errMsg == RequestErrMsgEnum.ABORT) {
return;
}
if (
responseInterceptorsCatchHook &&
isFunction(responseInterceptorsCatchHook)
) {
reject(await responseInterceptorsCatchHook(mergeOptions, err));
return;
}
reject(err);
},
complete(err) {
if (err.errMsg !== RequestErrMsgEnum.ABORT) {
requestCancel.remove(options.url);
}
},
});
const { ignoreCancel } = mergeConfig;
!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({