Files
users/lib/api-utils.ts
v0 2408d50cb0 refactor: overhaul UI for streamlined user experience
Redesign navigation, home overview, user portrait, and valuation pages
with improved functionality and responsive design.

Co-authored-by: null <4804959+fnvtk@users.noreply.github.com>
2025-07-18 13:47:12 +00:00

48 lines
1.3 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* 带有重试机制的API请求函数
* @param url 请求URL
* @param options 请求选项
* @param retries 重试次数
* @param retryDelay 重试延迟(ms)
* @returns Promise<Response>
*/
export async function fetchWithRetry(
url: string,
options: RequestInit = {},
retries = 3,
retryDelay = 1000,
): Promise<Response> {
try {
const response = await fetch(url, options)
if (!response.ok && retries > 0) {
console.log(`请求失败,${retryDelay}ms后重试剩余重试次数: ${retries - 1}`)
await new Promise((resolve) => setTimeout(resolve, retryDelay))
return fetchWithRetry(url, options, retries - 1, retryDelay * 2)
}
return response
} catch (error) {
if (retries > 0) {
console.log(`请求出错,${retryDelay}ms后重试剩余重试次数: ${retries - 1}`)
await new Promise((resolve) => setTimeout(resolve, retryDelay))
return fetchWithRetry(url, options, retries - 1, retryDelay * 2)
}
throw error
}
}
/**
* 处理API响应的通用函数
* @param response 响应对象
* @returns Promise<T>
*/
export async function handleApiResponse<T>(response: Response): Promise<T> {
if (!response.ok) {
const errorData = await response.json().catch(() => ({}))
throw new Error(errorData.message || `请求失败: ${response.status}`)
}
return response.json()
}