From 6996bb72e3d60935f505b9a446942997a415b400 Mon Sep 17 00:00:00 2001 From: Rewrite0 <49576640+Rewrite0@users.noreply.github.com> Date: Wed, 31 May 2023 22:06:04 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BC=98=E5=8C=96=20useApi=20hook?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/hooks/useApi.ts | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/src/hooks/useApi.ts b/src/hooks/useApi.ts index 179c2a74..5242bb04 100644 --- a/src/hooks/useApi.ts +++ b/src/hooks/useApi.ts @@ -1,14 +1,17 @@ type AnyAsyncFuntion = (...args: any[]) => Promise; +type UnPromisify = T extends AnyAsyncFuntion ? U : never; export function useApi< TError = any, TApi extends AnyAsyncFuntion = AnyAsyncFuntion, - TData = ReturnType + TData = UnPromisify >( api: TApi, options?: { + failRule?: (data: TData) => boolean; message?: { success?: string; + fail?: string; error?: string; }; } @@ -24,13 +27,17 @@ export function useApi< isLoading.value = true; api(...params) - .then((res) => { + .then((res: TData) => { data.value = res; fetchResult.trigger(res); + if (options?.failRule && options.failRule(res)) { + options.message?.fail && message.error(options.message.fail); + } + options?.message?.success && message.success(options.message.success); }) - .catch((err) => { + .catch((err: TError) => { fetchError.trigger(err); options?.message?.error && message.error(options.message.error);