2026-07-30 17:59:42 +08:00
|
|
|
import axios, { AxiosError, type AxiosRequestConfig, type InternalAxiosRequestConfig } from 'axios'
|
2026-07-30 21:23:06 +08:00
|
|
|
import { parseApiJsonResponse } from '@chongchong/shared'
|
2026-07-30 17:59:42 +08:00
|
|
|
import { clearSessionTokens, getAccessToken, getRefreshToken, persistTokenPair, type TokenPair } from '@/api/session'
|
2026-08-06 18:02:02 +08:00
|
|
|
import { apiErrorMessage, asFieldErrors } from '@/api/errorDetails'
|
|
|
|
|
import { ApiError, isApiEnvelope, type ApiEnvelope } from '@/api/types'
|
2026-07-30 17:59:42 +08:00
|
|
|
|
|
|
|
|
const transport = axios.create({
|
|
|
|
|
baseURL: import.meta.env.VITE_API_BASE_URL || '/api',
|
|
|
|
|
timeout: 15_000,
|
2026-07-30 21:23:06 +08:00
|
|
|
transformResponse: [(data: unknown) => parseApiJsonResponse(data)],
|
2026-07-30 17:59:42 +08:00
|
|
|
})
|
|
|
|
|
|
|
|
|
|
interface RetryableRequest extends InternalAxiosRequestConfig {
|
|
|
|
|
_retriedAfterRefresh?: boolean
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function unwrap<T>(envelope: ApiEnvelope<T>) {
|
2026-08-01 12:17:33 +08:00
|
|
|
if (envelope.code !== '200') {
|
2026-08-06 18:02:02 +08:00
|
|
|
const fieldErrors = asFieldErrors(envelope.data)
|
|
|
|
|
throw new ApiError(apiErrorMessage(envelope.message, fieldErrors), envelope.code, undefined, fieldErrors, envelope.traceId)
|
2026-07-30 17:59:42 +08:00
|
|
|
}
|
|
|
|
|
return envelope.data
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function mapError(error: unknown) {
|
|
|
|
|
if (error instanceof ApiError) return error
|
|
|
|
|
if (!axios.isAxiosError(error)) return new ApiError(error instanceof Error ? error.message : '请求失败')
|
|
|
|
|
|
|
|
|
|
const body = error.response?.data
|
|
|
|
|
if (isApiEnvelope(body)) {
|
2026-08-06 18:02:02 +08:00
|
|
|
const fieldErrors = asFieldErrors(body.data)
|
2026-07-30 17:59:42 +08:00
|
|
|
return new ApiError(
|
2026-08-06 18:02:02 +08:00
|
|
|
apiErrorMessage(body.message, fieldErrors),
|
2026-07-30 17:59:42 +08:00
|
|
|
body.code,
|
|
|
|
|
error.response?.status,
|
2026-08-06 18:02:02 +08:00
|
|
|
fieldErrors,
|
2026-07-30 17:59:42 +08:00
|
|
|
typeof body.traceId === 'string' ? body.traceId : null,
|
|
|
|
|
)
|
|
|
|
|
}
|
|
|
|
|
if (error.code === AxiosError.ERR_NETWORK) return new ApiError('无法连接服务器,请确认后端服务已启动', 'NETWORK_ERROR')
|
|
|
|
|
if (error.code === AxiosError.ECONNABORTED) return new ApiError('请求超时,请稍后重试', 'TIMEOUT')
|
|
|
|
|
return new ApiError(error.message || '请求失败', 'HTTP_ERROR', error.response?.status)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
let refreshPromise: Promise<TokenPair> | null = null
|
2026-08-01 12:17:33 +08:00
|
|
|
let redirectingToLogin = false
|
|
|
|
|
|
|
|
|
|
function redirectToLoginAfterSessionExpiry() {
|
|
|
|
|
if (redirectingToLogin || typeof window === 'undefined') return
|
|
|
|
|
|
|
|
|
|
const { pathname, search, hash } = window.location
|
|
|
|
|
if (pathname === '/login' || pathname === '/register') return
|
|
|
|
|
|
|
|
|
|
redirectingToLogin = true
|
|
|
|
|
const redirect = `${pathname}${search}${hash}`
|
|
|
|
|
window.location.replace(`/login?redirect=${encodeURIComponent(redirect)}`)
|
|
|
|
|
}
|
2026-07-30 17:59:42 +08:00
|
|
|
|
|
|
|
|
async function refreshSession() {
|
|
|
|
|
const refreshToken = getRefreshToken()
|
|
|
|
|
if (!refreshToken) throw new ApiError('登录已过期,请重新登录', 'A0401', 401)
|
|
|
|
|
if (!refreshPromise) {
|
|
|
|
|
refreshPromise = transport
|
|
|
|
|
.post<ApiEnvelope<TokenPair>>('/auth/refresh', { refreshToken })
|
|
|
|
|
.then((response) => unwrap(response.data))
|
|
|
|
|
.then((tokens) => {
|
|
|
|
|
persistTokenPair(tokens)
|
|
|
|
|
return tokens
|
|
|
|
|
})
|
|
|
|
|
.finally(() => {
|
|
|
|
|
refreshPromise = null
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
return refreshPromise
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
transport.interceptors.request.use((config) => {
|
|
|
|
|
const token = getAccessToken()
|
|
|
|
|
if (token) config.headers.Authorization = `Bearer ${token}`
|
|
|
|
|
return config
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
transport.interceptors.response.use(
|
|
|
|
|
(response) => response,
|
|
|
|
|
async (error: AxiosError) => {
|
|
|
|
|
const request = error.config as RetryableRequest | undefined
|
|
|
|
|
const publicAuthPaths = ['/auth/login', '/auth/register', '/auth/refresh']
|
|
|
|
|
const isPublicAuthRequest = publicAuthPaths.some((path) => request?.url?.endsWith(path))
|
|
|
|
|
if (error.response?.status !== 401 || !request || request._retriedAfterRefresh || isPublicAuthRequest) {
|
|
|
|
|
throw mapError(error)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
request._retriedAfterRefresh = true
|
|
|
|
|
try {
|
|
|
|
|
const tokens = await refreshSession()
|
|
|
|
|
request.headers.Authorization = `Bearer ${tokens.accessToken}`
|
|
|
|
|
return await transport.request(request)
|
|
|
|
|
} catch (refreshError) {
|
2026-07-30 21:23:06 +08:00
|
|
|
const mappedError = mapError(refreshError)
|
|
|
|
|
if (mappedError.status === 401 || mappedError.code === 'A0401') {
|
|
|
|
|
clearSessionTokens()
|
|
|
|
|
window.dispatchEvent(new CustomEvent('cc-client-session-expired'))
|
2026-08-01 12:17:33 +08:00
|
|
|
redirectToLoginAfterSessionExpiry()
|
2026-07-30 21:23:06 +08:00
|
|
|
}
|
|
|
|
|
throw mappedError
|
2026-07-30 17:59:42 +08:00
|
|
|
}
|
|
|
|
|
},
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
export async function apiRequest<T>(config: AxiosRequestConfig) {
|
|
|
|
|
try {
|
|
|
|
|
const response = await transport.request<ApiEnvelope<T>>(config)
|
|
|
|
|
return unwrap(response.data)
|
|
|
|
|
} catch (error) {
|
|
|
|
|
throw mapError(error)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export async function apiBlobRequest(config: AxiosRequestConfig) {
|
|
|
|
|
try {
|
|
|
|
|
const response = await transport.request<Blob>({ ...config, responseType: 'blob' })
|
|
|
|
|
return response.data
|
|
|
|
|
} catch (error) {
|
|
|
|
|
throw mapError(error)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export { ApiError }
|