From 9b3cc2deb5d2a96ed66fe67a513e802f95481347 Mon Sep 17 00:00:00 2001 From: Jin Mao Date: Mon, 25 Aug 2025 06:43:59 +0800 Subject: [PATCH] =?UTF-8?q?refactor(alova):=20=E9=87=8D=E6=9E=84=E5=93=8D?= =?UTF-8?q?=E5=BA=94=E6=88=90=E5=8A=9F=E6=8B=A6=E6=88=AA=E5=99=A8=E5=A4=84?= =?UTF-8?q?=E7=90=86=E9=80=BB=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit -移除自定义 ResponseData 接口,使用 alova 的 Response接口 - 重新定义 responseSuccessInterceptor 类型为 ResponseSuccessHandler - 优化响应成功拦截器的执行流程 - 移除不必要的错误抛出和 JSON 解析 --- packages/effects/plugins/src/alova/index.ts | 41 +++++---------------- 1 file changed, 10 insertions(+), 31 deletions(-) diff --git a/packages/effects/plugins/src/alova/index.ts b/packages/effects/plugins/src/alova/index.ts index 62e709c1a..e68c9f303 100644 --- a/packages/effects/plugins/src/alova/index.ts +++ b/packages/effects/plugins/src/alova/index.ts @@ -9,6 +9,7 @@ import type { RespondedAlovaGenerics, ResponseCompleteHandler, ResponseErrorHandler, + ResponseSuccessHandler, StatesHook, } from 'alova'; import type { @@ -27,23 +28,6 @@ type RequestMethod = ( method: Method, ) => Promise | void; -/** - * 标准响应数据结构 - */ -interface ResponseData { - code?: number; - data?: T; - message?: string; - [key: string]: unknown; -} - -/** - * 响应成功拦截器方法类型 - */ -type ResponseSuccessMethod = ( - json: ResponseData, -) => Promise>; - /** * Alova HTTP客户端封装类 * @template T 泛型参数,继承自AlovaGenerics @@ -69,7 +53,7 @@ class AlovaClient { /** * 请求成功拦截器数组 */ - public responseSuccessInterceptor: ResponseSuccessMethod[] = []; + public responseSuccessInterceptor: ResponseSuccessHandler[] = []; /** * 构造函数 * @param options Alova配置选项 @@ -77,12 +61,12 @@ class AlovaClient { */ constructor( options: AlovaOptions, - authOptions: TokenAuthenticationResult< + authOptions?: TokenAuthenticationResult< StatesHook, AlovaRequestAdapterUnified - > = {}, + >, ) { - const { onAuthRequired, onResponseRefreshToken } = authOptions; + const { onAuthRequired, onResponseRefreshToken } = authOptions || {}; const beforeRequest = async (method: Method) => { for (const interceptor of this.requestInterceptor) { await interceptor(method); @@ -93,17 +77,13 @@ class AlovaClient { // 当使用 `alova/fetch` 请求适配器时,第一个参数接收Response对象 // 第二个参数为当前请求的method实例,你可以用它同步请求前后的配置信息 onSuccess: async (response: Response, method: Method) => { - if (response.status >= 400) { - throw new Error(response.statusText); - } - const json = await response.json(); - - let result = json; + let result: any = null; for (const interceptor of this.responseSuccessInterceptor) { - result = await interceptor(json); + result = await interceptor(response, method); + if (result) { + return result; + } } - - return result; }, onError: async (err: Error, method: Method) => { @@ -124,7 +104,6 @@ class AlovaClient { }; this.instance = createAlova({ - baseURL: '', requestAdapter: adapterFetch(), statesHook: VueHook, beforeRequest: onAuthRequired