xuexiaole-mobile/src/api/request.ts
2025-08-02 12:49:52 +08:00

93 lines
2.6 KiB
TypeScript

import { user } from '@/store'
import { storeToRefs } from 'pinia'
import { getCache } from '@/utils'
import router from '@/router/router'
import db from '@/utils/db'
const CONFIG = {
baseURL: `${import.meta.env.VITE_HOST}/api/main`,
// baseURL: '/api/main',
timeout: 60000,
method: 'GET',
}
export class HttpError extends Error {
data: any
constructor(message: string, data: Record<string, any>) {
super(message)
this.data = data
}
}
const request = async (config: Record<string, any>): Promise<any> => {
const networkType = await uni.getNetworkType()
if (networkType.networkType === 'none') {
uni.showModal({
content: '暂无网络,请恢复网络后使用',
confirmText: '知道了',
showCancel: false,
confirmColor: '#ffe60f',
})
return Promise.reject(
new HttpError('暂无网络,请恢复网络后使用', {
code: '-1',
}),
)
}
return new Promise((resolve, reject) => {
const { clear } = user()
const { token } = storeToRefs(user())
const mergerToken = token.value || db.get('token')
const method = (config.method || CONFIG.method).toUpperCase()
uni.request({
method,
// url: (config.host || CONFIG.host) + (config.baseURL || CONFIG.baseURL) + config.url,
url: (config.baseURL || CONFIG.baseURL) + config.url,
data: method === 'GET' ? config.params : config.data,
timeout: config.timeout || CONFIG.timeout,
header: {
Authorization: mergerToken ? `Bearer ${mergerToken}` : '',
...config.headers,
},
complete(res: any) {
if (res.statusCode === 200) {
if (res.data.code === 200) {
return resolve(res.data)
} else {
if (!config.showToast) {
uni.showToast({
title: res.data?.message,
icon: 'none',
duration: 3000,
})
}
return reject(new HttpError(res.data?.message, res.data))
}
} else {
res.href = (config.baseURL || CONFIG.baseURL) + config.url
if (res.statusCode === 401) {
clear()
router.reLaunch('/pages/login/index')
} else {
uni.showToast({
icon: 'none',
title:
res.statusCode === 500 ? '服务异常' : res?.data?.message || '服务异常,请稍后重试',
})
}
return reject(
new HttpError(res.data?.message, {
code: res.statusCode,
data: res.data,
}),
)
}
},
})
})
}
export default request