@kevairy/template 0.1.2 → 0.1.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/template/.env +4 -0
- package/template/.env.production +6 -0
- package/template/.prettierignore +2 -0
- package/template/_gitignore +4 -1
- package/template/package.json +10 -0
- package/template/scripts/gen-offline-icons.mjs +84 -0
- package/template/src/adapters/auth/index.ts +1 -1
- package/template/src/adapters/auth/types.ts +6 -1
- package/template/src/api/auth.ts +3 -2
- package/template/src/components/core/forms/art-wang-editor/index.vue +0 -5
- package/template/src/components/core/layouts/art-guide/index.vue +131 -0
- package/template/src/components/core/layouts/art-header-bar/index.vue +26 -26
- package/template/src/components/core/layouts/art-header-bar/widget/ArtUserMenu.vue +17 -1
- package/template/src/components/core/layouts/art-page-content/index.vue +8 -1
- package/template/src/components/core/layouts/art-screen-lock/index.vue +325 -0
- package/template/src/components/core/layouts/art-settings-panel/widget/SettingActions.vue +0 -1
- package/template/src/components/core/media/art-cutter-img/index.vue +0 -1
- package/template/src/components/core/media/art-video-player/index.vue +0 -10
- package/template/src/config/index.ts +8 -1
- package/template/src/config/modules/component.ts +14 -0
- package/template/src/config/modules/guide.ts +122 -0
- package/template/src/config/modules/headerBar.ts +4 -0
- package/template/src/config/setting.ts +2 -2
- package/template/src/directives/core/access.ts +125 -0
- package/template/src/directives/core/auth.ts +7 -62
- package/template/src/directives/core/roles.ts +5 -83
- package/template/src/env.d.ts +1 -0
- package/template/src/hooks/core/useAuth.ts +2 -74
- package/template/src/hooks/core/useGuide.ts +122 -0
- package/template/src/hooks/core/useHeaderBar.ts +6 -0
- package/template/src/hooks/core/usePermission.ts +41 -0
- package/template/src/hooks/index.ts +1 -0
- package/template/src/locales/index.ts +0 -1
- package/template/src/locales/langs/en.json +77 -6
- package/template/src/locales/langs/zh.json +77 -6
- package/template/src/main.ts +19 -9
- package/template/src/router/core/IframeRouteManager.ts +4 -2
- package/template/src/router/core/MenuProcessor.ts +5 -40
- package/template/src/router/core/RoutePermissionValidator.ts +6 -149
- package/template/src/router/core/access.ts +79 -0
- package/template/src/router/guards/afterEach.ts +6 -10
- package/template/src/router/guards/beforeEach.ts +143 -100
- package/template/src/router/guards/error.ts +42 -0
- package/template/src/router/index.ts +2 -0
- package/template/src/router/modules/examples.ts +4 -3
- package/template/src/router/routes/staticRoutes.ts +5 -3
- package/template/src/services/auth.ts +32 -10
- package/template/src/services/permission.ts +21 -0
- package/template/src/store/modules/lock.ts +125 -0
- package/template/src/store/modules/menu.ts +28 -8
- package/template/src/store/modules/setting.ts +8 -15
- package/template/src/store/modules/user.ts +73 -33
- package/template/src/store/modules/worktab.ts +1 -1
- package/template/src/types/api/api.d.ts +4 -1
- package/template/src/types/config/index.ts +9 -0
- package/template/src/types/directive/directive.d.ts +1 -0
- package/template/src/types/import/components.d.ts +2 -0
- package/template/src/types/router/index.ts +6 -0
- package/template/src/utils/http/contract.ts +51 -19
- package/template/src/utils/http/error.ts +73 -26
- package/template/src/utils/http/index.ts +160 -165
- package/template/src/utils/http/request-manager.ts +124 -0
- package/template/src/utils/http/status.ts +1 -0
- package/template/src/utils/permission/index.ts +66 -0
- package/template/src/utils/session.ts +24 -0
- package/template/src/utils/socket/index.ts +27 -2
- package/template/src/utils/storage/storage-config.ts +15 -0
- package/template/src/utils/storage/storage.ts +5 -3
- package/template/src/utils/sys/diagnostics.ts +180 -0
- package/template/src/utils/sys/error-handle.ts +56 -126
- package/template/src/utils/sys/mittBus.ts +5 -0
- package/template/src/utils/sys/recovery.ts +31 -0
- package/template/src/utils/ui/iconify-loader.ts +32 -18
- package/template/src/utils/ui/offline-icons.json +77 -0
- package/template/src/views/examples/permissions/index.vue +69 -13
- package/template/src/views/examples/search-table/index.vue +2 -3
- package/template/src/views/exception/403/index.vue +33 -0
- package/template/src/views/exception/500/index.vue +52 -10
- package/template/tests/e2e/auth.spec.ts +24 -6
- package/template/tests/e2e/helpers/guide.ts +9 -0
- package/template/tests/e2e/permissions.spec.ts +53 -0
- package/template/tests/e2e/search-table.spec.ts +2 -0
- package/template/tests/e2e/session-recovery.spec.ts +49 -0
- package/template/tests/unit/diagnostics/diagnostics.spec.ts +132 -0
- package/template/tests/unit/diagnostics/router.spec.ts +84 -0
- package/template/tests/unit/http/auth-lifecycle.spec.ts +203 -0
- package/template/tests/unit/http/contract.spec.ts +46 -0
- package/template/tests/unit/http/request.spec.ts +487 -0
- package/template/tests/unit/permissions/guard.spec.ts +261 -0
- package/template/tests/unit/permissions/guide.spec.ts +30 -0
- package/template/tests/unit/permissions/rules.spec.ts +106 -0
- package/template/tests/unit/permissions/state-and-directives.spec.ts +176 -0
- package/template/tests/unit/router/examples.spec.ts +5 -1
- package/template/vite.config.ts +8 -2
|
@@ -21,9 +21,13 @@
|
|
|
21
21
|
* @module utils/http/error
|
|
22
22
|
* @author Art Design Pro Team
|
|
23
23
|
*/
|
|
24
|
-
import {
|
|
24
|
+
import { isAxiosError, isCancel } from 'axios'
|
|
25
|
+
import { ElMessage } from 'element-plus'
|
|
25
26
|
import { ApiStatus } from './status'
|
|
26
27
|
import { $t } from '@/locales'
|
|
28
|
+
import { reportDiagnostic } from '@/utils/sys/diagnostics'
|
|
29
|
+
|
|
30
|
+
export type HttpErrorKind = 'business' | 'http' | 'network' | 'timeout' | 'cancelled' | 'config'
|
|
27
31
|
|
|
28
32
|
// 错误响应接口
|
|
29
33
|
export interface ErrorResponse {
|
|
@@ -37,6 +41,7 @@ export interface ErrorResponse {
|
|
|
37
41
|
|
|
38
42
|
// 错误日志数据接口
|
|
39
43
|
export interface ErrorLogData {
|
|
44
|
+
kind?: HttpErrorKind
|
|
40
45
|
/** 错误状态码 */
|
|
41
46
|
code: number
|
|
42
47
|
/** 错误消息 */
|
|
@@ -55,6 +60,7 @@ export interface ErrorLogData {
|
|
|
55
60
|
|
|
56
61
|
// 自定义 HttpError 类
|
|
57
62
|
export class HttpError extends Error {
|
|
63
|
+
public readonly kind: HttpErrorKind
|
|
58
64
|
public readonly code: number
|
|
59
65
|
public readonly data?: unknown
|
|
60
66
|
public readonly timestamp: string
|
|
@@ -65,6 +71,7 @@ export class HttpError extends Error {
|
|
|
65
71
|
message: string,
|
|
66
72
|
code: number,
|
|
67
73
|
options?: {
|
|
74
|
+
kind?: HttpErrorKind
|
|
68
75
|
data?: unknown
|
|
69
76
|
url?: string
|
|
70
77
|
method?: string
|
|
@@ -73,6 +80,7 @@ export class HttpError extends Error {
|
|
|
73
80
|
super(message)
|
|
74
81
|
this.name = 'HttpError'
|
|
75
82
|
this.code = code
|
|
83
|
+
this.kind = options?.kind ?? 'business'
|
|
76
84
|
this.data = options?.data
|
|
77
85
|
this.timestamp = new Date().toISOString()
|
|
78
86
|
this.url = options?.url
|
|
@@ -82,6 +90,7 @@ export class HttpError extends Error {
|
|
|
82
90
|
public toLogData(): ErrorLogData {
|
|
83
91
|
return {
|
|
84
92
|
code: this.code,
|
|
93
|
+
kind: this.kind,
|
|
85
94
|
message: this.message,
|
|
86
95
|
data: this.data,
|
|
87
96
|
timestamp: this.timestamp,
|
|
@@ -118,36 +127,69 @@ const getErrorMessage = (status: number): string => {
|
|
|
118
127
|
* @param error 错误对象
|
|
119
128
|
* @returns 错误对象
|
|
120
129
|
*/
|
|
121
|
-
export function
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
130
|
+
export function toHttpError(error: unknown): HttpError {
|
|
131
|
+
if (error instanceof HttpError) return error
|
|
132
|
+
const axiosError = isAxiosError<ErrorResponse & { message?: string }>(error) ? error : undefined
|
|
133
|
+
const context = {
|
|
134
|
+
url: axiosError?.config?.url,
|
|
135
|
+
method: axiosError?.config?.method?.toUpperCase()
|
|
126
136
|
}
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
url: requestConfig?.url,
|
|
136
|
-
method: requestConfig?.method?.toUpperCase()
|
|
137
|
+
if (
|
|
138
|
+
isCancel(error) ||
|
|
139
|
+
axiosError?.code === 'ERR_CANCELED' ||
|
|
140
|
+
(error instanceof Error && error.name === 'AbortError')
|
|
141
|
+
) {
|
|
142
|
+
return new HttpError($t('httpMsg.requestCancelled'), ApiStatus.requestCancelled, {
|
|
143
|
+
...context,
|
|
144
|
+
kind: 'cancelled'
|
|
137
145
|
})
|
|
138
146
|
}
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
147
|
+
if (axiosError?.response) {
|
|
148
|
+
const status = axiosError.response.status
|
|
149
|
+
return new HttpError(getErrorMessage(status), status, {
|
|
150
|
+
...context,
|
|
151
|
+
kind: 'http',
|
|
152
|
+
data: axiosError.response.data
|
|
153
|
+
})
|
|
154
|
+
}
|
|
155
|
+
if (axiosError?.code === 'ECONNABORTED' || axiosError?.code === 'ETIMEDOUT') {
|
|
156
|
+
return new HttpError($t('httpMsg.requestTimeout'), ApiStatus.requestTimeout, {
|
|
157
|
+
...context,
|
|
158
|
+
kind: 'timeout'
|
|
159
|
+
})
|
|
160
|
+
}
|
|
161
|
+
if (
|
|
162
|
+
axiosError &&
|
|
163
|
+
(axiosError.request ||
|
|
164
|
+
['ERR_NETWORK', 'ENOTFOUND', 'ECONNRESET', 'ECONNREFUSED', 'EAI_AGAIN'].includes(
|
|
165
|
+
axiosError.code ?? ''
|
|
166
|
+
))
|
|
167
|
+
) {
|
|
168
|
+
return new HttpError($t('httpMsg.networkError'), ApiStatus.error, {
|
|
169
|
+
...context,
|
|
170
|
+
kind: 'network'
|
|
171
|
+
})
|
|
172
|
+
}
|
|
173
|
+
return new HttpError($t('httpMsg.requestConfigError'), ApiStatus.error, {
|
|
174
|
+
...context,
|
|
175
|
+
kind: 'config'
|
|
148
176
|
})
|
|
149
177
|
}
|
|
150
178
|
|
|
179
|
+
/** 兼容已有调用:转换后抛出统一错误。 */
|
|
180
|
+
export function handleError(error: unknown): never {
|
|
181
|
+
throw toHttpError(error)
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
export function isRequestCanceled(error: unknown): boolean {
|
|
185
|
+
return (
|
|
186
|
+
(error instanceof HttpError && error.kind === 'cancelled') ||
|
|
187
|
+
isCancel(error) ||
|
|
188
|
+
(isAxiosError(error) && error.code === 'ERR_CANCELED') ||
|
|
189
|
+
(error instanceof Error && error.name === 'AbortError')
|
|
190
|
+
)
|
|
191
|
+
}
|
|
192
|
+
|
|
151
193
|
/**
|
|
152
194
|
* 显示错误消息
|
|
153
195
|
* @param error 错误对象
|
|
@@ -158,7 +200,12 @@ export function showError(error: HttpError, showMessage: boolean = true): void {
|
|
|
158
200
|
ElMessage.error(error.message)
|
|
159
201
|
}
|
|
160
202
|
// 记录错误日志
|
|
161
|
-
|
|
203
|
+
reportDiagnostic('http', error, {
|
|
204
|
+
code: error.code,
|
|
205
|
+
errorKind: error.kind,
|
|
206
|
+
url: error.url,
|
|
207
|
+
method: error.method
|
|
208
|
+
})
|
|
162
209
|
}
|
|
163
210
|
|
|
164
211
|
/**
|
|
@@ -1,44 +1,48 @@
|
|
|
1
|
-
import axios, {
|
|
2
|
-
AxiosRequestConfig,
|
|
3
|
-
AxiosResponse,
|
|
4
|
-
InternalAxiosRequestConfig,
|
|
5
|
-
isAxiosError
|
|
6
|
-
} from 'axios'
|
|
1
|
+
import axios, { AxiosHeaders, type AxiosRequestConfig, type AxiosResponse } from 'axios'
|
|
7
2
|
import { useUserStore } from '@/store/modules/user'
|
|
8
3
|
import { ApiStatus } from './status'
|
|
9
|
-
import { HttpError,
|
|
4
|
+
import { HttpError, toHttpError, showError, showSuccess } from './error'
|
|
10
5
|
import { $t } from '@/locales'
|
|
11
6
|
import type { BaseResponse } from '@/types'
|
|
12
7
|
import { createRequestKey, isApiSuccessCode, normalizeApiCode } from './contract'
|
|
8
|
+
import {
|
|
9
|
+
beginRequest,
|
|
10
|
+
runWithSignal,
|
|
11
|
+
throwIfAborted,
|
|
12
|
+
waitForRetry,
|
|
13
|
+
type RequestScope
|
|
14
|
+
} from './request-manager'
|
|
15
|
+
|
|
16
|
+
export { cancelAllPendingRequests } from './request-manager'
|
|
17
|
+
export { isRequestCanceled } from './error'
|
|
13
18
|
|
|
14
19
|
const REQUEST_TIMEOUT = 15000
|
|
15
|
-
const MAX_RETRIES = 0
|
|
16
20
|
const RETRY_DELAY = 1000
|
|
17
21
|
const UNAUTHORIZED_DEBOUNCE_TIME = 3000
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
+
let unauthorizedUntil = 0
|
|
23
|
+
|
|
24
|
+
export interface RetryOptions {
|
|
25
|
+
/** 首次发送之外的额外尝试次数,默认读取 VITE_HTTP_MAX_RETRIES。 */
|
|
26
|
+
retries?: number
|
|
27
|
+
/** 两次尝试间隔,毫秒,默认 1000。 */
|
|
28
|
+
delay?: number
|
|
29
|
+
/** 写请求仅在确认后端幂等后显式开启。 */
|
|
30
|
+
allowUnsafe?: boolean
|
|
31
|
+
}
|
|
22
32
|
|
|
23
33
|
export interface ExtendedAxiosRequestConfig extends AxiosRequestConfig {
|
|
24
|
-
/** 是否展示业务错误消息,默认展示 */
|
|
25
34
|
showErrorMessage?: boolean
|
|
26
|
-
/** 是否展示业务成功消息,默认不展示 */
|
|
27
35
|
showSuccessMessage?: boolean
|
|
28
|
-
/**
|
|
36
|
+
/** 默认并行。显式 true 才取消同 scope、同 key 的上一个逻辑请求。 */
|
|
29
37
|
cancelPrevious?: boolean
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
interface TrackedRequestConfig extends InternalAxiosRequestConfig {
|
|
38
|
+
/** 可显式分组不同参数的请求;上传等数据仅在显式指定 key 时去重。 */
|
|
33
39
|
requestKey?: string
|
|
34
|
-
|
|
35
|
-
|
|
40
|
+
/** 各页面/组件可用独立的 string 或 Symbol 防止互相取消。 */
|
|
41
|
+
requestScope?: RequestScope
|
|
42
|
+
retry?: false | RetryOptions
|
|
36
43
|
}
|
|
37
44
|
|
|
38
45
|
const { VITE_API_URL, VITE_WITH_CREDENTIALS, VITE_AUTH_SCHEME } = import.meta.env
|
|
39
|
-
const pendingRequests = new Map<string, AbortController>()
|
|
40
|
-
let requestSequence = 0
|
|
41
|
-
|
|
42
46
|
const axiosInstance = axios.create({
|
|
43
47
|
timeout: REQUEST_TIMEOUT,
|
|
44
48
|
baseURL: VITE_API_URL,
|
|
@@ -46,181 +50,172 @@ const axiosInstance = axios.create({
|
|
|
46
50
|
validateStatus: (status) => status >= 200 && status < 300
|
|
47
51
|
})
|
|
48
52
|
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
const scheme = VITE_AUTH_SCHEME ? `${VITE_AUTH_SCHEME.trim()} ` : ''
|
|
54
|
-
request.headers.set('Authorization', `${scheme}${userStore.accessToken}`)
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
if (request.data && !(request.data instanceof FormData) && !request.headers['Content-Type']) {
|
|
58
|
-
request.headers.set('Content-Type', 'application/json')
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
const baseRequestKey = createRequestKey(request)
|
|
62
|
-
const requestKey =
|
|
63
|
-
request.cancelPrevious === false ? `${baseRequestKey}|${++requestSequence}` : baseRequestKey
|
|
64
|
-
request.requestKey = requestKey
|
|
65
|
-
|
|
66
|
-
if (request.cancelPrevious !== false) {
|
|
67
|
-
pendingRequests.get(baseRequestKey)?.abort('Duplicated request cancelled')
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
const controller = new AbortController()
|
|
71
|
-
request.abortController = controller
|
|
72
|
-
request.signal = controller.signal
|
|
73
|
-
pendingRequests.set(requestKey, controller)
|
|
53
|
+
function nonNegativeInteger(value: unknown, fallback: number): number {
|
|
54
|
+
const number = Number(value)
|
|
55
|
+
return Number.isFinite(number) && number >= 0 ? Math.floor(number) : fallback
|
|
56
|
+
}
|
|
74
57
|
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
58
|
+
function retryPolicy(config: ExtendedAxiosRequestConfig) {
|
|
59
|
+
const safe = ['GET', 'HEAD'].includes(config.method?.toUpperCase() || 'GET')
|
|
60
|
+
const options = config.retry === false ? undefined : config.retry
|
|
61
|
+
return {
|
|
62
|
+
retries:
|
|
63
|
+
config.retry === false || (!safe && options?.allowUnsafe !== true)
|
|
64
|
+
? 0
|
|
65
|
+
: options?.retries === undefined
|
|
66
|
+
? nonNegativeInteger(import.meta.env.VITE_HTTP_MAX_RETRIES, 0)
|
|
67
|
+
: nonNegativeInteger(options.retries, 0),
|
|
68
|
+
delay: nonNegativeInteger(options?.delay, RETRY_DELAY)
|
|
81
69
|
}
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
axiosInstance.interceptors.response.use(
|
|
85
|
-
(response: AxiosResponse<BaseResponse>) => {
|
|
86
|
-
removePendingRequest(response.config as TrackedRequestConfig)
|
|
87
|
-
|
|
88
|
-
if (response.status === 204) {
|
|
89
|
-
return response
|
|
90
|
-
}
|
|
70
|
+
}
|
|
91
71
|
|
|
92
|
-
|
|
93
|
-
|
|
72
|
+
function shouldRetry(error: HttpError): boolean {
|
|
73
|
+
if (error.kind === 'network' || error.kind === 'timeout') return true
|
|
74
|
+
return error.kind === 'http' && [408, 500, 502, 503, 504].includes(error.code)
|
|
75
|
+
}
|
|
94
76
|
|
|
95
|
-
|
|
96
|
-
|
|
77
|
+
function prepareHeaders(config: AxiosRequestConfig): AxiosHeaders {
|
|
78
|
+
if (config.headers instanceof AxiosHeaders) return new AxiosHeaders(config.headers)
|
|
79
|
+
const raw = config.headers ?? {}
|
|
80
|
+
const groups = raw as Partial<Record<string, ConstructorParameters<typeof AxiosHeaders>[0]>>
|
|
81
|
+
const methodHeaders = [
|
|
82
|
+
'common',
|
|
83
|
+
'get',
|
|
84
|
+
'head',
|
|
85
|
+
'post',
|
|
86
|
+
'put',
|
|
87
|
+
'patch',
|
|
88
|
+
'delete',
|
|
89
|
+
'options',
|
|
90
|
+
'query'
|
|
91
|
+
]
|
|
92
|
+
const flat = Object.fromEntries(
|
|
93
|
+
Object.entries(raw).filter(([name]) => !methodHeaders.includes(name))
|
|
94
|
+
)
|
|
95
|
+
return AxiosHeaders.concat(
|
|
96
|
+
groups.common,
|
|
97
|
+
groups[(config.method || 'GET').toLowerCase()],
|
|
98
|
+
flat as ConstructorParameters<typeof AxiosHeaders>[0]
|
|
99
|
+
)
|
|
100
|
+
}
|
|
97
101
|
|
|
98
|
-
|
|
102
|
+
function unwrap<T>(response: AxiosResponse<BaseResponse<T>>): T {
|
|
103
|
+
if (response.status === 204 || response.config.method?.toUpperCase() === 'HEAD')
|
|
104
|
+
return undefined as T
|
|
105
|
+
const code = normalizeApiCode(response.data?.code)
|
|
106
|
+
if (isApiSuccessCode(code)) return response.data.data
|
|
107
|
+
throw new HttpError(
|
|
108
|
+
response.data?.message || response.data?.msg || $t('httpMsg.requestFailed'),
|
|
109
|
+
code,
|
|
110
|
+
{
|
|
111
|
+
kind: 'business',
|
|
99
112
|
data: response.data?.data,
|
|
100
113
|
url: response.config.url,
|
|
101
114
|
method: response.config.method?.toUpperCase()
|
|
102
|
-
})
|
|
103
|
-
},
|
|
104
|
-
(error) => {
|
|
105
|
-
if (error?.config) removePendingRequest(error.config as TrackedRequestConfig)
|
|
106
|
-
if (error instanceof HttpError) return Promise.reject(error)
|
|
107
|
-
|
|
108
|
-
if (axios.isCancel(error) || error?.code === 'ERR_CANCELED') {
|
|
109
|
-
return Promise.reject(
|
|
110
|
-
createHttpError($t('httpMsg.requestCancelled'), REQUEST_CANCELLED_CODE, {
|
|
111
|
-
url: error?.config?.url,
|
|
112
|
-
method: error?.config?.method?.toUpperCase()
|
|
113
|
-
})
|
|
114
|
-
)
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
if (isAxiosError(error) && error.response?.status === ApiStatus.unauthorized) {
|
|
118
|
-
handleUnauthorizedError(error.response.data?.message || error.response.data?.msg)
|
|
119
115
|
}
|
|
120
|
-
|
|
121
|
-
return Promise.reject(handleError(error))
|
|
122
|
-
}
|
|
123
|
-
)
|
|
124
|
-
|
|
125
|
-
function createHttpError(
|
|
126
|
-
message: string,
|
|
127
|
-
code: number,
|
|
128
|
-
options?: { data?: unknown; url?: string; method?: string }
|
|
129
|
-
) {
|
|
130
|
-
return new HttpError(message, code, options)
|
|
116
|
+
)
|
|
131
117
|
}
|
|
132
118
|
|
|
133
|
-
function
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
if (
|
|
137
|
-
|
|
138
|
-
useUserStore().clearAuthState()
|
|
139
|
-
unauthorizedTimer = setTimeout(resetUnauthorizedError, UNAUTHORIZED_DEBOUNCE_TIME)
|
|
119
|
+
function handleUnauthorized(error: HttpError): void {
|
|
120
|
+
// 清理会话始终执行;时间窗口只控制提示,不能让新会话的 401 被忽略。
|
|
121
|
+
useUserStore().clearAuthState()
|
|
122
|
+
if (Date.now() >= unauthorizedUntil) {
|
|
123
|
+
unauthorizedUntil = Date.now() + UNAUTHORIZED_DEBOUNCE_TIME
|
|
140
124
|
showError(error)
|
|
141
125
|
}
|
|
142
|
-
|
|
143
|
-
throw error
|
|
144
|
-
}
|
|
145
|
-
|
|
146
|
-
function resetUnauthorizedError() {
|
|
147
|
-
isUnauthorizedErrorShown = false
|
|
148
|
-
if (unauthorizedTimer) clearTimeout(unauthorizedTimer)
|
|
149
|
-
unauthorizedTimer = null
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
function removePendingRequest(config: TrackedRequestConfig): void {
|
|
153
|
-
if (!config.requestKey) return
|
|
154
|
-
if (pendingRequests.get(config.requestKey) === config.abortController) {
|
|
155
|
-
pendingRequests.delete(config.requestKey)
|
|
156
|
-
}
|
|
157
|
-
}
|
|
158
|
-
|
|
159
|
-
/** 取消当前尚未完成的全部请求。 */
|
|
160
|
-
export function cancelAllPendingRequests(): void {
|
|
161
|
-
pendingRequests.forEach((controller) => controller.abort('All pending requests cancelled'))
|
|
162
|
-
pendingRequests.clear()
|
|
163
126
|
}
|
|
164
127
|
|
|
165
|
-
function
|
|
166
|
-
return
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
ApiStatus.gatewayTimeout
|
|
172
|
-
].includes(statusCode)
|
|
173
|
-
}
|
|
174
|
-
|
|
175
|
-
async function retryRequest<T>(
|
|
176
|
-
config: ExtendedAxiosRequestConfig,
|
|
177
|
-
retries: number = MAX_RETRIES
|
|
178
|
-
): Promise<T> {
|
|
179
|
-
try {
|
|
180
|
-
return await request<T>(config)
|
|
181
|
-
} catch (error) {
|
|
182
|
-
if (retries > 0 && error instanceof HttpError && shouldRetry(error.code)) {
|
|
183
|
-
await new Promise((resolve) => setTimeout(resolve, RETRY_DELAY))
|
|
184
|
-
return retryRequest<T>(config, retries - 1)
|
|
185
|
-
}
|
|
186
|
-
throw error
|
|
187
|
-
}
|
|
128
|
+
function cancelledError(config: ExtendedAxiosRequestConfig): HttpError {
|
|
129
|
+
return new HttpError($t('httpMsg.requestCancelled'), ApiStatus.requestCancelled, {
|
|
130
|
+
kind: 'cancelled',
|
|
131
|
+
url: config.url,
|
|
132
|
+
method: config.method?.toUpperCase() || 'GET'
|
|
133
|
+
})
|
|
188
134
|
}
|
|
189
135
|
|
|
190
136
|
async function request<T = unknown>(config: ExtendedAxiosRequestConfig): Promise<T> {
|
|
137
|
+
let managed: ReturnType<typeof beginRequest> | undefined
|
|
191
138
|
try {
|
|
192
|
-
|
|
193
|
-
const
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
139
|
+
if (config.signal?.aborted) throw cancelledError(config)
|
|
140
|
+
const { cancelPrevious, requestKey, requestScope, retry, ...axiosConfig } = config
|
|
141
|
+
const headers = prepareHeaders(config)
|
|
142
|
+
const token = useUserStore().accessToken
|
|
143
|
+
if (token) {
|
|
144
|
+
const scheme = VITE_AUTH_SCHEME?.trim()
|
|
145
|
+
headers.set('Authorization', scheme ? `${scheme} ${token}` : token)
|
|
146
|
+
}
|
|
147
|
+
const prepared = {
|
|
148
|
+
...axiosConfig,
|
|
149
|
+
method: (config.method || 'GET').toUpperCase(),
|
|
150
|
+
baseURL: config.baseURL ?? VITE_API_URL,
|
|
151
|
+
headers
|
|
152
|
+
}
|
|
153
|
+
if (requestKey !== undefined && !requestKey.trim())
|
|
154
|
+
throw new TypeError('requestKey must not be empty')
|
|
155
|
+
const key =
|
|
156
|
+
cancelPrevious === true
|
|
157
|
+
? (requestKey ??
|
|
158
|
+
createRequestKey({
|
|
159
|
+
...prepared,
|
|
160
|
+
headers: Object.fromEntries(
|
|
161
|
+
Object.entries(headers).map(([name, value]) => [name.toLowerCase(), value])
|
|
162
|
+
)
|
|
163
|
+
}))
|
|
164
|
+
: undefined
|
|
165
|
+
managed = beginRequest({ signal: config.signal, key, scope: requestScope })
|
|
166
|
+
const signal = managed.signal
|
|
167
|
+
const policy = retryPolicy({ ...config, retry })
|
|
168
|
+
for (let attempt = 0; ; attempt++) {
|
|
169
|
+
throwIfAborted(signal)
|
|
170
|
+
try {
|
|
171
|
+
const response = await runWithSignal(
|
|
172
|
+
() => axiosInstance.request<BaseResponse<T>>({ ...prepared, signal }),
|
|
173
|
+
signal
|
|
174
|
+
)
|
|
175
|
+
throwIfAborted(signal)
|
|
176
|
+
const data = unwrap(response)
|
|
177
|
+
const message = response.data?.message || response.data?.msg
|
|
178
|
+
if (config.showSuccessMessage && message) showSuccess(message)
|
|
179
|
+
return data
|
|
180
|
+
} catch (caught) {
|
|
181
|
+
throwIfAborted(signal)
|
|
182
|
+
const error = toHttpError(caught)
|
|
183
|
+
if (attempt >= policy.retries || !shouldRetry(error)) throw error
|
|
184
|
+
await waitForRetry(policy.delay, signal)
|
|
202
185
|
}
|
|
203
186
|
}
|
|
204
|
-
|
|
187
|
+
} catch (caught) {
|
|
188
|
+
const error = managed?.signal.aborted ? cancelledError(config) : toHttpError(caught)
|
|
189
|
+
// 先释放当前任务,再让 401 清理其它请求,保留当前错误的 401 语义。
|
|
190
|
+
managed?.finish()
|
|
191
|
+
if (
|
|
192
|
+
error.code === ApiStatus.unauthorized &&
|
|
193
|
+
(error.kind === 'http' || error.kind === 'business')
|
|
194
|
+
) {
|
|
195
|
+
handleUnauthorized(error)
|
|
196
|
+
} else if (error.kind !== 'cancelled') {
|
|
197
|
+
showError(error, config.showErrorMessage !== false)
|
|
198
|
+
}
|
|
199
|
+
throw error
|
|
200
|
+
} finally {
|
|
201
|
+
managed?.finish()
|
|
205
202
|
}
|
|
206
203
|
}
|
|
207
204
|
|
|
208
205
|
const api = {
|
|
209
206
|
get<T>(config: ExtendedAxiosRequestConfig) {
|
|
210
|
-
return
|
|
207
|
+
return request<T>({ ...config, method: 'GET' })
|
|
211
208
|
},
|
|
212
209
|
post<T>(config: ExtendedAxiosRequestConfig) {
|
|
213
|
-
return
|
|
210
|
+
return request<T>({ ...config, method: 'POST' })
|
|
214
211
|
},
|
|
215
212
|
put<T>(config: ExtendedAxiosRequestConfig) {
|
|
216
|
-
return
|
|
213
|
+
return request<T>({ ...config, method: 'PUT' })
|
|
217
214
|
},
|
|
218
215
|
del<T>(config: ExtendedAxiosRequestConfig) {
|
|
219
|
-
return
|
|
216
|
+
return request<T>({ ...config, method: 'DELETE' })
|
|
220
217
|
},
|
|
221
|
-
request
|
|
222
|
-
return retryRequest<T>(config)
|
|
223
|
-
}
|
|
218
|
+
request
|
|
224
219
|
}
|
|
225
220
|
|
|
226
221
|
export default api
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import type { AxiosRequestConfig } from 'axios'
|
|
2
|
+
|
|
3
|
+
export type RequestScope = string | symbol
|
|
4
|
+
|
|
5
|
+
interface ManagedRequest {
|
|
6
|
+
signal: AbortSignal
|
|
7
|
+
finish: () => void
|
|
8
|
+
cancel: () => void
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
const activeRequests = new Set<ManagedRequest>()
|
|
12
|
+
const requestGroups = new Map<RequestScope, Map<string, ManagedRequest>>()
|
|
13
|
+
let sessionVersion = 0
|
|
14
|
+
let sessionClosing = false
|
|
15
|
+
/** 仅远端退出请求可在退出阶段使用此 scope。 */
|
|
16
|
+
export const SIGN_OUT_REQUEST_SCOPE = Symbol('sign-out')
|
|
17
|
+
|
|
18
|
+
export function getSessionVersion(): number {
|
|
19
|
+
return sessionVersion
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** 认证边界调用;普通页面取消不改变会话标识。 */
|
|
23
|
+
export function invalidateSessionRequests(): void {
|
|
24
|
+
sessionVersion++
|
|
25
|
+
sessionClosing = false
|
|
26
|
+
cancelAllPendingRequests()
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function closeSessionRequests(): void {
|
|
30
|
+
invalidateSessionRequests()
|
|
31
|
+
sessionClosing = true
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** 管理一次逻辑请求,包含所有尝试及重试等待;不依赖认证 Store。 */
|
|
35
|
+
export function beginRequest(options: {
|
|
36
|
+
signal?: AxiosRequestConfig['signal']
|
|
37
|
+
key?: string
|
|
38
|
+
scope?: RequestScope
|
|
39
|
+
}): ManagedRequest {
|
|
40
|
+
const controller = new AbortController()
|
|
41
|
+
const scope = options.scope ?? 'global'
|
|
42
|
+
const source = options.signal
|
|
43
|
+
const onSourceAbort = () => controller.abort('Caller cancelled')
|
|
44
|
+
let finished = false
|
|
45
|
+
const request: ManagedRequest = {
|
|
46
|
+
signal: controller.signal,
|
|
47
|
+
cancel: () => controller.abort('Request cancelled'),
|
|
48
|
+
finish: () => {
|
|
49
|
+
if (finished) return
|
|
50
|
+
finished = true
|
|
51
|
+
source?.removeEventListener?.('abort', onSourceAbort)
|
|
52
|
+
controller.signal.removeEventListener('abort', request.finish)
|
|
53
|
+
activeRequests.delete(request)
|
|
54
|
+
if (options.key !== undefined) {
|
|
55
|
+
const group = requestGroups.get(scope)
|
|
56
|
+
if (group?.get(options.key) === request) group.delete(options.key)
|
|
57
|
+
if (group?.size === 0) requestGroups.delete(scope)
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// 已取消的新请求不能取消同组中仍有效的旧请求。
|
|
63
|
+
if (source?.aborted || (sessionClosing && scope !== SIGN_OUT_REQUEST_SCOPE)) {
|
|
64
|
+
controller.abort('Caller cancelled')
|
|
65
|
+
return request
|
|
66
|
+
}
|
|
67
|
+
source?.addEventListener?.('abort', onSourceAbort, { once: true })
|
|
68
|
+
controller.signal.addEventListener('abort', request.finish, { once: true })
|
|
69
|
+
if (options.key !== undefined) {
|
|
70
|
+
requestGroups.get(scope)?.get(options.key)?.cancel()
|
|
71
|
+
const group = requestGroups.get(scope) ?? new Map<string, ManagedRequest>()
|
|
72
|
+
group.set(options.key, request)
|
|
73
|
+
requestGroups.set(scope, group)
|
|
74
|
+
}
|
|
75
|
+
activeRequests.add(request)
|
|
76
|
+
return request
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** 包括重试等待中的任务;取消后新建的请求使用独立控制器。 */
|
|
80
|
+
export function cancelAllPendingRequests(): void {
|
|
81
|
+
for (const request of [...activeRequests]) request.cancel()
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export function throwIfAborted(signal: AbortSignal): void {
|
|
85
|
+
if (signal.aborted) throw new DOMException('Request cancelled', 'AbortError')
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** 即使自定义 transport 忽略 signal,也不交付过期响应或处理其 401。 */
|
|
89
|
+
export function runWithSignal<T>(task: () => Promise<T>, signal: AbortSignal): Promise<T> {
|
|
90
|
+
return new Promise((resolve, reject) => {
|
|
91
|
+
const abort = () => reject(new DOMException('Request cancelled', 'AbortError'))
|
|
92
|
+
if (signal.aborted) {
|
|
93
|
+
abort()
|
|
94
|
+
return
|
|
95
|
+
}
|
|
96
|
+
signal.addEventListener('abort', abort, { once: true })
|
|
97
|
+
Promise.resolve()
|
|
98
|
+
.then(() => {
|
|
99
|
+
throwIfAborted(signal)
|
|
100
|
+
return task()
|
|
101
|
+
})
|
|
102
|
+
.then(resolve, reject)
|
|
103
|
+
.finally(() => signal.removeEventListener('abort', abort))
|
|
104
|
+
})
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export function waitForRetry(delay: number, signal: AbortSignal): Promise<void> {
|
|
108
|
+
return new Promise((resolve, reject) => {
|
|
109
|
+
if (signal.aborted) {
|
|
110
|
+
reject(new DOMException('Request cancelled', 'AbortError'))
|
|
111
|
+
return
|
|
112
|
+
}
|
|
113
|
+
const abort = () => {
|
|
114
|
+
clearTimeout(timer)
|
|
115
|
+
signal.removeEventListener('abort', abort)
|
|
116
|
+
reject(new DOMException('Request cancelled', 'AbortError'))
|
|
117
|
+
}
|
|
118
|
+
const timer = setTimeout(() => {
|
|
119
|
+
signal.removeEventListener('abort', abort)
|
|
120
|
+
resolve()
|
|
121
|
+
}, delay)
|
|
122
|
+
signal.addEventListener('abort', abort, { once: true })
|
|
123
|
+
})
|
|
124
|
+
}
|