feat: Features架构迁移 - P0和P1部分完成
## 完成的工作 ### P0: 基础设施准备 - 创建 features/ 和 shared/ 目录结构 - 迁移共享资源:API基础设施、工具函数、类型定义 - 迁移通用composables:useMoney, useSmsCountdown, usePricingCalculator - 迁移全局样式文件 - 建立模块化导出系统 ### P1.1: 钱包模块 (wallet) - 迁移 API: wallet.ts - 迁移 Views: WalletView.vue - 新增 Composable: useWallet.ts (封装钱包状态管理) - 更新导入路径到 shared/ ### P1.2: 聊天模块 (chats) - 迁移 API: chats.ts - 迁移 Views: ChatView, MessagesView (桌面+移动) - 迁移 Composables: useChatSSE.ts - 迁移 Components: ChatAttachmentImage.vue - 更新导入路径到 shared/ ## 技术改进 - 修复 shared/composables 导出问题 (default → 命名导出) - 修复 shared/api/client.ts 类型导入路径 - 建立清晰的模块边界和导出规范 ## 文档 - 添加完整的迁移计划文档 - 添加进度跟踪文档 Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 4.7
parent
10acca637e
commit
b5903a169f
@@ -0,0 +1,172 @@
|
||||
import axios, { type AxiosResponse, type InternalAxiosRequestConfig } from 'axios'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { showToast } from 'vant'
|
||||
|
||||
function showError(message: string) {
|
||||
const isMobile = window.location.pathname.startsWith('/m')
|
||||
if (isMobile) {
|
||||
showToast({ message, icon: 'cross' })
|
||||
} else {
|
||||
ElMessage.error(message)
|
||||
}
|
||||
}
|
||||
|
||||
declare module 'axios' {
|
||||
export interface AxiosRequestConfig {
|
||||
silent?: boolean
|
||||
}
|
||||
}
|
||||
|
||||
import {
|
||||
clearAuthStorage,
|
||||
getAccessToken,
|
||||
getLoginPath,
|
||||
getRefreshToken,
|
||||
setAuthTokens,
|
||||
type AuthScope,
|
||||
} from '@/utils/authStorage'
|
||||
import type { ApiResponse } from '@/shared/types/types'
|
||||
|
||||
export const apiClient = axios.create({
|
||||
baseURL: '/api',
|
||||
timeout: 10000,
|
||||
})
|
||||
|
||||
export async function unwrapData<T>(request: Promise<AxiosResponse<ApiResponse<T>>>) {
|
||||
const { data } = await request
|
||||
return data.data
|
||||
}
|
||||
|
||||
type RetryRequest = {
|
||||
resolve: (token: string) => void
|
||||
reject: (error: unknown) => void
|
||||
}
|
||||
|
||||
type RefreshState = {
|
||||
refreshing: boolean
|
||||
pendingRequests: RetryRequest[]
|
||||
}
|
||||
|
||||
type RetriableRequestConfig = InternalAxiosRequestConfig & {
|
||||
_retry?: boolean
|
||||
silent?: boolean
|
||||
}
|
||||
|
||||
const refreshStates: Record<AuthScope, RefreshState> = {
|
||||
user: {
|
||||
refreshing: false,
|
||||
pendingRequests: [],
|
||||
},
|
||||
admin: {
|
||||
refreshing: false,
|
||||
pendingRequests: [],
|
||||
},
|
||||
}
|
||||
|
||||
function resolvePendingRequests(scope: AuthScope, token: string) {
|
||||
const pendingRequests = refreshStates[scope].pendingRequests.splice(0)
|
||||
pendingRequests.forEach(({ resolve }) => resolve(token))
|
||||
}
|
||||
|
||||
function rejectPendingRequests(scope: AuthScope, error: unknown) {
|
||||
const pendingRequests = refreshStates[scope].pendingRequests.splice(0)
|
||||
pendingRequests.forEach(({ reject }) => reject(error))
|
||||
}
|
||||
|
||||
export async function refreshAccessToken(scope: AuthScope): Promise<string> {
|
||||
const refreshToken = getRefreshToken(scope)
|
||||
if (!refreshToken) throw new Error('no refresh token')
|
||||
|
||||
const endpoint = scope === 'admin' ? '/api/admin/auth/refresh' : '/api/auth/refresh'
|
||||
const { data } = await axios.post(endpoint, { refresh_token: refreshToken }, { timeout: 10000 })
|
||||
const tokens = {
|
||||
access_token: data.data.access_token,
|
||||
refresh_token: data.data.refresh_token,
|
||||
}
|
||||
setAuthTokens(scope, tokens)
|
||||
return tokens.access_token
|
||||
}
|
||||
|
||||
function getRequestScope(url = ''): AuthScope {
|
||||
return url.startsWith('/admin') ? 'admin' : 'user'
|
||||
}
|
||||
|
||||
function redirectToLogin(scope: AuthScope) {
|
||||
clearAuthStorage(scope)
|
||||
const currentPath = window.location.pathname + window.location.search
|
||||
const loginPath = getLoginPath(scope, currentPath)
|
||||
if (currentPath.startsWith(loginPath)) return
|
||||
|
||||
if (scope === 'admin') {
|
||||
window.location.assign(loginPath)
|
||||
return
|
||||
}
|
||||
|
||||
window.location.assign(`${loginPath}?redirect=${encodeURIComponent(currentPath)}`)
|
||||
}
|
||||
|
||||
function isRefreshRequest(url = '') {
|
||||
return url.endsWith('/auth/refresh') || url.endsWith('/admin/auth/refresh')
|
||||
}
|
||||
|
||||
apiClient.interceptors.request.use((config) => {
|
||||
const scope = getRequestScope(config.url || '')
|
||||
const token = getAccessToken(scope)
|
||||
if (token) {
|
||||
config.headers.Authorization = `Bearer ${token}`
|
||||
}
|
||||
return config
|
||||
})
|
||||
|
||||
apiClient.interceptors.response.use(
|
||||
(response) => response,
|
||||
async (error) => {
|
||||
const originalRequest = error.config as RetriableRequestConfig | undefined
|
||||
if (!originalRequest || error?.response?.status !== 401 || originalRequest._retry) {
|
||||
if (originalRequest && !originalRequest.silent) {
|
||||
const msg = error.response?.data?.message || error.message || '网络连接异常,请稍后重试'
|
||||
showError(msg)
|
||||
}
|
||||
return Promise.reject(error)
|
||||
}
|
||||
|
||||
const requestUrl = originalRequest.url || ''
|
||||
const scope = getRequestScope(requestUrl)
|
||||
if (isRefreshRequest(requestUrl)) {
|
||||
redirectToLogin(scope)
|
||||
if (originalRequest && !originalRequest.silent) {
|
||||
showError('登录已失效,请重新登录')
|
||||
}
|
||||
return Promise.reject(error)
|
||||
}
|
||||
|
||||
const state = refreshStates[scope]
|
||||
if (state.refreshing) {
|
||||
return new Promise<string>((resolve, reject) => {
|
||||
state.pendingRequests.push({ resolve, reject })
|
||||
}).then((newToken) => {
|
||||
originalRequest._retry = true
|
||||
originalRequest.headers.Authorization = `Bearer ${newToken}`
|
||||
return apiClient(originalRequest)
|
||||
})
|
||||
}
|
||||
|
||||
state.refreshing = true
|
||||
try {
|
||||
const newToken = await refreshAccessToken(scope)
|
||||
resolvePendingRequests(scope, newToken)
|
||||
originalRequest._retry = true
|
||||
originalRequest.headers.Authorization = `Bearer ${newToken}`
|
||||
return apiClient(originalRequest)
|
||||
} catch (refreshError) {
|
||||
rejectPendingRequests(scope, refreshError)
|
||||
redirectToLogin(scope)
|
||||
if (originalRequest && !originalRequest.silent) {
|
||||
showError('会话已过期,请重新登录')
|
||||
}
|
||||
return Promise.reject(refreshError)
|
||||
} finally {
|
||||
state.refreshing = false
|
||||
}
|
||||
},
|
||||
)
|
||||
@@ -0,0 +1,2 @@
|
||||
// API 基础设施
|
||||
export * from './client'
|
||||
Reference in New Issue
Block a user