feat(小程序): 修复运行时与登录链路

This commit is contained in:
stu2not
2026-04-22 17:25:03 +08:00
parent 24b1d1025b
commit d7df6f565c
12 changed files with 297 additions and 426 deletions

View File

@@ -1,7 +1,9 @@
import Taro from '@tarojs/taro'
import { API_BASE_URL } from '@/config/env'
import { getCurrentUserId, getToken, handleUnauthorized } from './session'
const BASE_URL = API_BASE_URL
const REQUEST_TIMEOUT_MS = 10000
class ApiError extends Error {
constructor(public status: number, message: string) {
@@ -9,6 +11,16 @@ class ApiError extends Error {
}
}
function getErrorDetail(data: any): string {
if (!data) return 'Request failed'
if (typeof data.detail === 'string') return data.detail
if (Array.isArray(data.detail)) {
return data.detail.map((item: any) => String(item?.msg || item)).join('; ')
}
if (typeof data.message === 'string') return data.message
return 'Request failed'
}
async function request<T>(
url: string,
options: {
@@ -17,40 +29,42 @@ async function request<T>(
headers?: Record<string, string>
} = {}
): Promise<T> {
const token = Taro.getStorageSync('token')
console.log(`[API] ${options.method || 'GET'} ${url}`, token ? 'with token' : 'no token')
const token = getToken()
const headers: Record<string, string> = {
'Content-Type': 'application/json',
...options.headers,
}
if (token) {
headers['Authorization'] = `Bearer ${token}`
headers.Authorization = `Bearer ${token}`
}
const response = await Taro.request({
url: `${BASE_URL}${url}`,
method: options.method || 'GET',
data: options.data,
header: headers,
})
let response
try {
response = await Taro.request({
url: `${BASE_URL}${url}`,
method: options.method || 'GET',
data: options.data,
header: headers,
timeout: REQUEST_TIMEOUT_MS,
})
} catch (error: any) {
const message = String(error?.errMsg || error?.message || '')
const detail = message.includes('timeout')
? '请求超时,请检查后端服务是否可访问'
: '网络请求失败,请检查后端地址和网络连接'
throw new ApiError(0, detail)
}
if (response.statusCode === 401) {
handleUnauthorized({ redirect: !url.startsWith('/auth/') })
}
console.log(`[API] Response status:`, response.statusCode)
if (response.statusCode >= 400) {
const detail = response.data?.detail || 'Request failed'
throw new ApiError(response.statusCode, detail)
throw new ApiError(response.statusCode, getErrorDetail(response.data))
}
return response.data
return response.data as T
}
export { request, ApiError, BASE_URL }
export function getToken(): string {
return Taro.getStorageSync('token') || ''
}
export function getCurrentUserId(): number {
return Taro.getStorageSync('user_id') || 0
}
export { getCurrentUserId, getToken }