From a1acba5085cabe78a6e9eef66acdf6a5750630db Mon Sep 17 00:00:00 2001 From: npmrun <1549469775@qq.com> Date: Sat, 18 Apr 2026 21:54:15 +0800 Subject: [PATCH] feat: add useClientApi fetchData with optional error toast Made-with: Cursor --- app/composables/useClientApi.ts | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 app/composables/useClientApi.ts diff --git a/app/composables/useClientApi.ts b/app/composables/useClientApi.ts new file mode 100644 index 0000000..3250fc5 --- /dev/null +++ b/app/composables/useClientApi.ts @@ -0,0 +1,24 @@ +import { request, unwrapApiBody, type ApiResponse } from '~/utils/http/factory' +import { getApiErrorMessage } from '~/utils/http/error-message' + +type RequestOptions = NonNullable[1]> +export type ClientFetchOptions = RequestOptions & { notify?: boolean } + +export function useClientApi() { + const toast = useToast() + + async function fetchData(url: string, options?: ClientFetchOptions): Promise { + const { notify = true, ...rest } = options ?? {} + try { + const res = await request>(url, rest) + return unwrapApiBody(res) + } catch (e: unknown) { + if (import.meta.client && notify) { + toast.add({ title: getApiErrorMessage(e), color: 'error' }) + } + throw e + } + } + + return { fetchData, getApiErrorMessage } +}