apiHander.ts
1.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/**
* API响应处理工具函数
* 统一处理API请求的成功/失败逻辑
*/
interface ApiResponse {
code: number;
data?: any;
msg?: string;
}
export interface ApiHandlerOptions {
/* 当前实例的proxy对象(用于获取$passCode和$ElMessage)*/
proxy: any
/** 加载状态ref */
loadingRef?: Ref<boolean>;
/** 成功回调函数 */
onSuccess?: (res: any) => void;
/** 失败回调函数 */
onError?: (res: any) => void;
/** 是否显示错误消息,默认true */
showError?: boolean;
}
/**
* 统一处理API响应的工具函数
* @param apiPromise API请求Promise
* @param options 配置选项
*/
export const handleApiResponse = async (
apiPromise: Promise<ApiResponse>,
options: ApiHandlerOptions,
) => {
const {
loadingRef,
onSuccess,
onError,
showError = true,
proxy
} = options;
try {
// 设置加载状态
if (loadingRef) {
loadingRef.value = true;
}
// 执行API请求
const res = await apiPromise;
// 设置加载状态
if (loadingRef) {
loadingRef.value = false;
}
// 判断请求是否成功
if (res?.code == proxy.$passCode) {
// 成功回调
onSuccess && onSuccess(res);
} else {
// 失败处理
const errorMsg = res?.msg || '';
if (showError) {
proxy.$ElMessage.error(errorMsg);
}
onError && onError(res);
}
} catch (error: any) {
// 异常处理
if (loadingRef) {
loadingRef.value = false;
}
}
};