Skip to content

Commit

Permalink
feat: 完善请求封装
Browse files Browse the repository at this point in the history
  • Loading branch information
mulingyuer committed Jan 16, 2025
1 parent b546188 commit 5324a5b
Show file tree
Hide file tree
Showing 9 changed files with 130 additions and 64 deletions.
1 change: 0 additions & 1 deletion .eslintrc-auto-import.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ module.exports = {
"DirectiveBinding": true,
"EffectScope": true,
"ElMessage": true,
"ElNotification": true,
"ExtractDefaultPropTypes": true,
"ExtractPropTypes": true,
"ExtractPublicPropTypes": true,
Expand Down
2 changes: 1 addition & 1 deletion src/api/auth/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/*
* @Author: mulingyuer
* @Date: 2024-09-27 15:32:20
* @LastEditTime: 2025-01-16 10:22:35
* @LastEditTime: 2025-01-16 15:42:09
* @LastEditors: mulingyuer
* @Description: auth请求接口
* @FilePath: \element-admin-template\src\api\auth\index.ts
Expand Down
28 changes: 28 additions & 0 deletions src/request/axios.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
/*
* @Author: mulingyuer
* @Date: 2025-01-16 15:34:55
* @LastEditTime: 2025-01-16 17:53:37
* @LastEditors: mulingyuer
* @Description: 扩展axios类型
* @FilePath: \element-admin-template\src\request\axios.d.ts
* 怎么可能会有bug!!!
*/
import "axios"; // 必须确保模块扩展的上下文是在 Axios 模块内

declare module "axios" {
interface AxiosRequestConfig {
/** 是否允许失败重试 */
enableRetry?: boolean;
/** 是否显示错误消息弹窗 */
showErrorMessage?: boolean;
/** 取消请求是否显示错误消息,注意:`showErrorMessage` 优先级大于该设置。
* 这个配置你得在cancel的时候设置,例:
* ```typescript
* const CancelToken = axios.CancelToken;
* const source = CancelToken.source();
* source.cancel("取消的原因", { showCancelErrorMessage: false });
* ```
*/
showCancelErrorMessage?: boolean;
}
}
60 changes: 25 additions & 35 deletions src/request/core.ts
Original file line number Diff line number Diff line change
@@ -1,28 +1,40 @@
/*
* @Author: mulingyuer
* @Date: 2024-09-25 16:18:26
* @LastEditTime: 2024-09-25 16:52:56
* @LastEditTime: 2025-01-16 17:55:25
* @LastEditors: mulingyuer
* @Description: 请求核心
* @FilePath: \spirit-app-microservice-admin\src\request\core.ts
* @FilePath: \element-admin-template\src\request\core.ts
* 怎么可能会有bug!!!
*/
import axios, { AxiosError } from "axios";
import axiosRetry from "axios-retry";
import type { RequestConfig } from "./types";
import { useUserStore } from "@/stores";
import axios from "axios";
import axiosRetry, { isNetworkOrIdempotentRequestError } from "axios-retry";
import { showMaxRetryErrorMessage, showRequestErrorMessage } from "./helper";

const instance = axios.create();
const instance = axios.create({
baseURL: import.meta.env.VITE_APP_API_BASE_URL,
enableRetry: true,
showErrorMessage: true,
// showCancelErrorMessage: true, // 这里配置无效,索性注释了
timeout: 15000 // ms
});
let userStore: ReturnType<typeof useUserStore>;

// 失败重试
axiosRetry(instance, {
retries: 3,
retryCondition(error: AxiosError) {
const config: RequestConfig | undefined = error?.config;
retryCondition(error) {
const config = error?.config;
if (!config) return false;
if (config.enableRetry) return true;
if (config.enableRetry && isNetworkOrIdempotentRequestError(error)) {
return true;
}
return false;
},
onMaxRetryTimesExceeded: (error) => {
// 显示错误消息
showMaxRetryErrorMessage(error);
}
});

Expand All @@ -45,33 +57,11 @@ instance.interceptors.response.use(
return response.data;
},
(error) => {
let message = "未知错误";
// 显示错误消息
showRequestErrorMessage(error);

if (axios.isCancel(error)) {
// 请求被取消
message = error.message ?? "请求被取消";
} else if (error instanceof AxiosError) {
// AxiosError
message = error.response?.data?.message ?? error.message;
} else if (error instanceof Error) {
// Error
message = error.message;
}

// 消息提示
ElNotification({
type: "error",
title: "请求失败",
message
});

return Promise.reject(new Error(message));
return Promise.reject(error as Error);
}
);

/** 设置请求的baseUrl */
function setBaseUrl(baseUrl: string) {
instance.defaults.baseURL = baseUrl;
}

export { instance, setBaseUrl };
export { instance };
68 changes: 68 additions & 0 deletions src/request/helper.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
/*
* @Author: mulingyuer
* @Date: 2025-01-16 15:48:18
* @LastEditTime: 2025-01-16 17:44:46
* @LastEditors: mulingyuer
* @Description: 请求辅助函数
* @FilePath: \element-admin-template\src\request\helper.ts
* 怎么可能会有bug!!!
*/
import { AxiosError } from "axios";
import axios from "axios";
import { isNetworkOrIdempotentRequestError } from "axios-retry";

/** 失败重试显示错误消息弹窗 */
export function showMaxRetryErrorMessage(error: AxiosError) {
if (shouldShowErrorMessage(error)) {
showErrorMessage(getErrorMessage(error));
}
}

/** 显示请求错误消息弹窗 */
export function showRequestErrorMessage(error: any) {
if (isRetryError(error)) return;
if (shouldShowErrorMessage(error)) {
showErrorMessage(getErrorMessage(error));
}
}

/** 显示错误消息 */
export function showErrorMessage(message: string) {
ElNotification({
type: "error",
title: "请求失败",
message: message ?? "请求失败"
});
}

/** 根据axios的config判断是否显示错误消息 */
function shouldShowErrorMessage(error: any) {
console.log("🚀 ~ shouldShowErrorMessage ~ error:", error);
if (!error.config) return true;
const config = (error as AxiosError)?.config;
const showErrorMessage = config?.showErrorMessage ?? true;
const showCancelErrorMessage = config?.showCancelErrorMessage ?? true;
// 取消请求
if (axios.isCancel(error)) {
return showErrorMessage && showCancelErrorMessage;
}
return showErrorMessage;
}

/** 是否是失败重试错误 */
function isRetryError(error: any) {
if (error instanceof AxiosError) {
const isRetry = error.config?.enableRetry ?? true;
return isRetry && isNetworkOrIdempotentRequestError(error);
}
return true;
}

/** 获取错误消息 */
function getErrorMessage(error: any): string {
if (axios.isCancel(error)) return error.message ?? "请求被取消";
if (error instanceof AxiosError) return error.response?.data?.message ?? error.message;
if (error instanceof Error) return error.message;

return "未知错误";
}
13 changes: 5 additions & 8 deletions src/request/index.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,16 @@
/*
* @Author: mulingyuer
* @Date: 2024-09-25 16:18:08
* @LastEditTime: 2024-09-25 16:54:57
* @LastEditTime: 2025-01-16 15:44:35
* @LastEditors: mulingyuer
* @Description: 请求封装
* @FilePath: \spirit-app-microservice-admin\src\request\index.ts
* @FilePath: \element-admin-template\src\request\index.ts
* 怎么可能会有bug!!!
*/
import { instance, setBaseUrl } from "./core";
import type { RequestConfig } from "./types";
export type * from "./types";
import { instance } from "./core";
import type { AxiosRequestConfig } from "axios";

/** 请求函数 */
export function request<T>(config: RequestConfig): Promise<T> {
export function request<T>(config: AxiosRequestConfig): Promise<T> {
return instance.request(config);
}

export { setBaseUrl };
16 changes: 0 additions & 16 deletions src/request/types.ts

This file was deleted.

4 changes: 2 additions & 2 deletions src/views/dashboard/index.vue
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
<!--
* @Author: mulingyuer
* @Date: 2024-09-26 12:16:02
* @LastEditTime: 2024-09-26 12:16:03
* @LastEditTime: 2025-01-16 17:56:59
* @LastEditors: mulingyuer
* @Description: 首页
* @FilePath: \spirit-app-microservice-admin\src\views\home\index.vue
* @FilePath: \element-admin-template\src\views\dashboard\index.vue
* 怎么可能会有bug!!!
-->
<template>
Expand Down
2 changes: 1 addition & 1 deletion tsconfig.app.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"extends": "@vue/tsconfig/tsconfig.dom.json",
"include": ["src/**/*", "src/**/*.vue", "types/**/*.d.ts"],
"include": ["src/**/*", "src/**/*.vue", "types/**/*.d.ts", "src/request/axios.d.ts"],
"exclude": ["src/**/__tests__/*"],
"compilerOptions": {
"composite": true,
Expand Down

0 comments on commit 5324a5b

Please sign in to comment.