Files
webgame-frontend/src/api/request/requestClient.ts
T

222 lines
6.3 KiB
TypeScript
Raw Normal View History

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()
}
2026-06-24 11:14:27 +08:00
// @ts-ignore
2026-06-09 10:12:09 +08:00
/** 注册请求和响应拦截器 */
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
// === 通用响应拦截器 ===
2026-06-24 11:14:27 +08:00
// 职责:解包 ApiResponse + 按 HTTP 状态码分类处理错误。
// HTTP 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-24 11:14:27 +08:00
// code !== 0 但 HTTP 2xx — 未改造端点或特殊场景,按业务错误处理
2026-06-16 18:19:48 +08:00
eventBus.emit(AppEvents.REQUEST_ERROR, {
2026-06-09 10:12:09 +08:00
type: 'business',
code: data.code,
2026-06-24 11:14:27 +08:00
httpStatus: response.status,
2026-06-09 10:12:09 +08:00
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-24 11:14:27 +08:00
const status = error.response?.status
2026-06-16 18:19:48 +08:00
// HTTP 401 透传给刷新拦截器
2026-06-24 11:14:27 +08:00
if (status === 401) {
2026-06-16 18:19:48 +08:00
throw error
2026-06-09 10:12:09 +08:00
}
2026-06-24 11:14:27 +08:00
// HTTP 400/403/404/409/405/500 — 从 body 提取 ApiResponse
const body = error.response?.data as ApiResponse | undefined
if (body && status) {
eventBus.emit(AppEvents.REQUEST_ERROR, {
type: 'business',
code: body.code,
httpStatus: status,
message: body.message || `请求错误 (${status})`
})
return Promise.reject(body)
}
// 网络异常(无 response)
2026-06-16 18:19:48 +08:00
eventBus.emit(AppEvents.REQUEST_ERROR, {
type: error.response ? 'http' : 'network',
2026-06-24 11:14:27 +08:00
code: status,
httpStatus: status,
message: 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
})
2026-06-24 11:14:27 +08:00
// 拦截器解包 axiosResponse → ApiResponse
2026-06-16 18:19:48 +08:00
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()