refactor(uniapp): 重构工具函数和请求模块,提取通用逻辑

This commit is contained in:
augushong
2026-02-01 12:34:50 +08:00
parent 83e6803a0a
commit 180d9291a3
3 changed files with 52 additions and 95 deletions

View File

@@ -0,0 +1,22 @@
export function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms))
}
export function omitEmpty(obj) {
const result = {}
if (!obj || typeof obj !== 'object') return result
Object.keys(obj).forEach((key) => {
const value = obj[key]
if (value === '' || value === null || value === undefined) return
result[key] = value
})
return result
}
export function toQueryString(params) {
const data = omitEmpty(params)
const parts = Object.keys(data).map((key) => `${encodeURIComponent(key)}=${encodeURIComponent(data[key])}`)
return parts.join('&')
}

View File

@@ -1,10 +1,11 @@
import { env } from '../config/env'
import { pinia } from '../store'
import { useUserStore } from '../store/user'
const AUTH_REQUIRED_CODE = 40101
const AUTH_EXPIRED_CODE = 40102
const TOKEN_KEY = 'ULTHON_ADMIN_TOKEN'
function buildUrl(url) {
if (!url) return ''
if (/^https?:\/\//i.test(url)) return url
@@ -36,7 +37,46 @@ function redirectToLoginIfNeeded() {
})
}
export function request(options) {
async function getUserStoreSafely() {
try {
const mod = await import('../store/user')
if (!mod || typeof mod.useUserStore !== 'function') return null
const userStore = mod.useUserStore(pinia)
if (userStore && typeof userStore.init === 'function') {
userStore.init()
}
return userStore || null
} catch (e) {
return null
}
}
function getTokenFromStorage() {
try {
return uni.getStorageSync(TOKEN_KEY) || ''
} catch (e) {
return ''
}
}
function clearTokenFromStorage() {
try {
uni.removeStorageSync(TOKEN_KEY)
} catch (e) {
}
}
async function handleAuthFailed() {
const userStore = await getUserStoreSafely()
if (userStore && typeof userStore.logout === 'function') {
userStore.logout()
} else {
clearTokenFromStorage()
}
redirectToLoginIfNeeded()
}
export async function request(options) {
const url = buildUrl(options.url)
const method = (options.method || 'GET').toUpperCase()
@@ -45,9 +85,8 @@ export function request(options) {
...(options.header || {}),
}
const userStore = useUserStore(pinia)
userStore.init()
const token = userStore.token
const silent = !!options.silent
const token = (options && options.token) || getTokenFromStorage()
if (token && !header.Authorization) {
header.Authorization = `Bearer ${token}`
}
@@ -67,13 +106,13 @@ export function request(options) {
const resData = res.data
if (!res || typeof res !== 'object') {
uni.showToast({ title: '请求失败', icon: 'none' })
if (!silent) uni.showToast({ title: '请求失败', icon: 'none' })
reject(new Error('Invalid response'))
return
}
if (res.statusCode && res.statusCode >= 400) {
uni.showToast({ title: `请求错误(${res.statusCode})`, icon: 'none' })
if (!silent) uni.showToast({ title: `请求错误(${res.statusCode})`, icon: 'none' })
reject(new Error(`HTTP ${res.statusCode}`))
return
}
@@ -85,11 +124,10 @@ export function request(options) {
}
if (resData.code === AUTH_REQUIRED_CODE || resData.code === AUTH_EXPIRED_CODE) {
userStore.logout()
redirectToLoginIfNeeded()
void handleAuthFailed()
}
uni.showToast({ title: resData.msg || '请求失败', icon: 'none' })
if (!silent) uni.showToast({ title: resData.msg || '请求失败', icon: 'none' })
reject(resData)
return
}
@@ -97,7 +135,7 @@ export function request(options) {
resolve(resData)
},
fail: (err) => {
uni.showToast({ title: '网络异常', icon: 'none' })
if (!silent) uni.showToast({ title: '网络异常', icon: 'none' })
reject(err)
},
})