2026-06-16 18:19:48 +08:00
|
|
|
import axios, { type AxiosInstance, type CreateAxiosDefaults } from 'axios'
|
2026-06-09 10:12:09 +08:00
|
|
|
import { useAccountStore } from '@/stores'
|
2026-06-16 10:45:14 +08:00
|
|
|
import { eventBus, AppEvents } from '@/utils'
|
2026-06-22 14:36:20 +08:00
|
|
|
import type { ApiResponse, InternalRequestConfig } from './types'
|
2026-06-16 18:19:48 +08:00
|
|
|
import { createRefreshTokenInterceptor } from './refreshInterceptor'
|
2026-06-09 10:12:09 +08:00
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* 替换 URL 中的路径参数占位符
|
|
|
|
|
*
|
|
|
|
|
* @example
|
|
|
|
|
* resolvePathParams('/user/:id/posts', { id: 1 }) // → '/user/1/posts'
|
|
|
|
|
*/
|
|
|
|
|
function resolvePathParams(url: string, pathParams?: Record<string, string | number>): string {
|
|
|
|
|
if (!pathParams) return url
|
|
|
|
|
return url.replace(/:(\w+)/g, (_, key) => {
|
|
|
|
|
const value = pathParams[key]
|
|
|
|
|
if (value === undefined) {
|
|
|
|
|
throw new Error(`路径参数 "${key}" 缺失`)
|
|
|
|
|
}
|
|
|
|
|
return String(value)
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* 基于 axios 封装的网络请求客户端
|
|
|
|
|
*
|
|
|
|
|
* 不依赖任何 UI 库,错误通过事件总线发布,由外部订阅处理。
|
|
|
|
|
*
|
|
|
|
|
* @example
|
|
|
|
|
* ```ts
|
|
|
|
|
* // GET 请求
|
|
|
|
|
* const res = await requestClient.get<UserListResult>('/users', { page: 1 })
|
|
|
|
|
*
|
|
|
|
|
* // POST 请求
|
|
|
|
|
* const res = await requestClient.post<LoginResult>('/auth/login', { username, password })
|
|
|
|
|
* ```
|
|
|
|
|
*/
|
|
|
|
|
class RequestClient {
|
2026-06-22 10:32:53 +08:00
|
|
|
/** axios 实例 */
|
2026-06-18 13:10:09 +08:00
|
|
|
public instance: AxiosInstance
|
2026-06-09 10:12:09 +08:00
|
|
|
|
2026-06-16 18:19:48 +08:00
|
|
|
/** 是否正在刷新 token */
|
|
|
|
|
isRefreshing = false
|
|
|
|
|
|
|
|
|
|
/** 刷新期间等待队列(401 请求在刷新完成前暂存,刷新后用新 token 重试) */
|
|
|
|
|
refreshTokenQueue: Array<(token: string) => void> = []
|
|
|
|
|
|
2026-06-09 10:12:09 +08:00
|
|
|
constructor(config?: CreateAxiosDefaults) {
|
|
|
|
|
this.instance = axios.create({
|
|
|
|
|
baseURL: '/api',
|
|
|
|
|
timeout: 15000,
|
|
|
|
|
headers: {
|
|
|
|
|
'Content-Type': 'application/json'
|
|
|
|
|
},
|
|
|
|
|
...config
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
this.setupInterceptors()
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/** 注册请求和响应拦截器 */
|
|
|
|
|
private setupInterceptors(): void {
|
|
|
|
|
// === 请求拦截器 ===
|
|
|
|
|
this.instance.interceptors.request.use(
|
|
|
|
|
(config) => {
|
|
|
|
|
const reqConfig = config as InternalRequestConfig
|
|
|
|
|
|
|
|
|
|
// 替换路径参数 :param → 实际值
|
|
|
|
|
if (reqConfig.pathParams && config.url) {
|
|
|
|
|
config.url = resolvePathParams(config.url, reqConfig.pathParams)
|
|
|
|
|
}
|
|
|
|
|
|
2026-06-16 18:19:48 +08:00
|
|
|
// 跳过鉴权时不注入 saToken
|
2026-06-09 10:12:09 +08:00
|
|
|
if (!reqConfig?.skipAuth) {
|
|
|
|
|
const accountStore = useAccountStore()
|
2026-06-16 16:16:47 +08:00
|
|
|
if (accountStore.accessToken) {
|
|
|
|
|
config.headers.saToken = accountStore.accessToken
|
2026-06-09 10:12:09 +08:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return config
|
|
|
|
|
},
|
|
|
|
|
(error) => {
|
|
|
|
|
return Promise.reject(error)
|
|
|
|
|
}
|
|
|
|
|
)
|
|
|
|
|
|
2026-06-16 18:19:48 +08:00
|
|
|
// === 通用响应拦截器 ===
|
|
|
|
|
// 职责:解包 ApiResponse + 发布非 401 的错误事件。
|
|
|
|
|
// 401 全部透传,由 refreshInterceptor 统一处理。
|
2026-06-09 10:12:09 +08:00
|
|
|
this.instance.interceptors.response.use(
|
|
|
|
|
// @ts-expect-error 拦截器解包 axiosResponse → ApiResponse
|
|
|
|
|
(response) => {
|
|
|
|
|
const data = response.data as ApiResponse
|
|
|
|
|
|
|
|
|
|
if (data.code === 0) {
|
|
|
|
|
return data
|
|
|
|
|
}
|
|
|
|
|
|
2026-06-16 18:19:48 +08:00
|
|
|
// 401 透传给刷新拦截器,此处不处理
|
|
|
|
|
if (data.code === 401) {
|
|
|
|
|
return response
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
eventBus.emit(AppEvents.REQUEST_ERROR, {
|
2026-06-09 10:12:09 +08:00
|
|
|
type: 'business',
|
|
|
|
|
code: data.code,
|
|
|
|
|
message: data.message || '请求失败'
|
2026-06-22 14:36:20 +08:00
|
|
|
})
|
2026-06-09 10:12:09 +08:00
|
|
|
return Promise.reject(data)
|
|
|
|
|
},
|
|
|
|
|
(error) => {
|
2026-06-16 18:19:48 +08:00
|
|
|
// HTTP 401 透传给刷新拦截器
|
2026-06-09 10:12:09 +08:00
|
|
|
if (error.response?.status === 401) {
|
2026-06-16 18:19:48 +08:00
|
|
|
throw error
|
2026-06-09 10:12:09 +08:00
|
|
|
}
|
|
|
|
|
|
2026-06-16 18:19:48 +08:00
|
|
|
eventBus.emit(AppEvents.REQUEST_ERROR, {
|
|
|
|
|
type: error.response ? 'http' : 'network',
|
|
|
|
|
code: error.response?.status,
|
|
|
|
|
message: error.response
|
|
|
|
|
? `请求错误 (${error.response.status})`
|
|
|
|
|
: '网络异常,请检查网络连接'
|
2026-06-22 14:36:20 +08:00
|
|
|
})
|
2026-06-09 10:12:09 +08:00
|
|
|
return Promise.reject(error)
|
|
|
|
|
}
|
|
|
|
|
)
|
2026-06-16 18:19:48 +08:00
|
|
|
|
|
|
|
|
// === Token 刷新拦截器 ===
|
|
|
|
|
// 通用拦截器透传 401 → 此处统一处理刷新/重试/重新认证
|
|
|
|
|
const { onFulfilled, onRejected } = createRefreshTokenInterceptor({
|
|
|
|
|
client: this.instance,
|
|
|
|
|
doReAuthenticate: async () => {
|
|
|
|
|
const accountStore = useAccountStore()
|
|
|
|
|
accountStore.logout()
|
|
|
|
|
eventBus.emit(AppEvents.UNAUTHORIZED)
|
|
|
|
|
},
|
|
|
|
|
doRefreshToken: () => {
|
|
|
|
|
const accountStore = useAccountStore()
|
|
|
|
|
return accountStore.refreshAccessToken()
|
|
|
|
|
},
|
|
|
|
|
formatToken: (token: string) => token,
|
|
|
|
|
isRefreshing: {
|
|
|
|
|
get value() {
|
|
|
|
|
return requestClient.isRefreshing
|
|
|
|
|
},
|
|
|
|
|
set value(v: boolean) {
|
|
|
|
|
requestClient.isRefreshing = v
|
|
|
|
|
}
|
|
|
|
|
},
|
|
|
|
|
refreshTokenQueue: this.refreshTokenQueue
|
|
|
|
|
})
|
|
|
|
|
// @ts-expect-error 拦截器解包 axiosResponse → ApiResponse
|
|
|
|
|
this.instance.interceptors.response.use(onFulfilled, onRejected)
|
2026-06-09 10:12:09 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* 通用请求方法
|
|
|
|
|
*
|
|
|
|
|
* 适用于路径参数、混合参数等复杂场景。
|
|
|
|
|
*/
|
|
|
|
|
request<T = unknown>(config: InternalRequestConfig): Promise<ApiResponse<T>> {
|
|
|
|
|
return this.instance.request(config)
|
|
|
|
|
}
|
|
|
|
|
|
2026-06-16 18:19:48 +08:00
|
|
|
/** GET 请求 */
|
2026-06-09 10:12:09 +08:00
|
|
|
get<T = unknown>(
|
|
|
|
|
url: string,
|
|
|
|
|
params?: Record<string, unknown>,
|
|
|
|
|
config?: InternalRequestConfig
|
|
|
|
|
): Promise<ApiResponse<T>> {
|
|
|
|
|
return this.instance.get(url, { params, ...config })
|
|
|
|
|
}
|
|
|
|
|
|
2026-06-16 18:19:48 +08:00
|
|
|
/** POST 请求 */
|
2026-06-09 10:12:09 +08:00
|
|
|
post<T = unknown>(
|
|
|
|
|
url: string,
|
|
|
|
|
data?: unknown,
|
|
|
|
|
config?: InternalRequestConfig
|
|
|
|
|
): Promise<ApiResponse<T>> {
|
|
|
|
|
return this.instance.post(url, data, config)
|
|
|
|
|
}
|
|
|
|
|
|
2026-06-16 18:19:48 +08:00
|
|
|
/** PUT 请求 */
|
2026-06-09 10:12:09 +08:00
|
|
|
put<T = unknown>(
|
|
|
|
|
url: string,
|
|
|
|
|
data?: unknown,
|
|
|
|
|
config?: InternalRequestConfig
|
|
|
|
|
): Promise<ApiResponse<T>> {
|
|
|
|
|
return this.instance.put(url, data, config)
|
|
|
|
|
}
|
|
|
|
|
|
2026-06-16 18:19:48 +08:00
|
|
|
/** DELETE 请求 */
|
2026-06-09 10:12:09 +08:00
|
|
|
delete<T = unknown>(url: string, config?: InternalRequestConfig): Promise<ApiResponse<T>> {
|
|
|
|
|
return this.instance.delete(url, config)
|
|
|
|
|
}
|
|
|
|
|
|
2026-06-16 18:19:48 +08:00
|
|
|
/** PATCH 请求 */
|
2026-06-09 10:12:09 +08:00
|
|
|
patch<T = unknown>(
|
|
|
|
|
url: string,
|
|
|
|
|
data?: unknown,
|
|
|
|
|
config?: InternalRequestConfig
|
|
|
|
|
): Promise<ApiResponse<T>> {
|
|
|
|
|
return this.instance.patch(url, data, config)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/** 请求客户端单例 */
|
|
|
|
|
export const requestClient = new RequestClient()
|