1 changed files with 24 additions and 0 deletions
@ -0,0 +1,24 @@ |
|||||
|
import { request, unwrapApiBody, type ApiResponse } from '~/utils/http/factory' |
||||
|
import { getApiErrorMessage } from '~/utils/http/error-message' |
||||
|
|
||||
|
type RequestOptions = NonNullable<Parameters<typeof request>[1]> |
||||
|
export type ClientFetchOptions = RequestOptions & { notify?: boolean } |
||||
|
|
||||
|
export function useClientApi() { |
||||
|
const toast = useToast() |
||||
|
|
||||
|
async function fetchData<T>(url: string, options?: ClientFetchOptions): Promise<T> { |
||||
|
const { notify = true, ...rest } = options ?? {} |
||||
|
try { |
||||
|
const res = await request<ApiResponse<T>>(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 } |
||||
|
} |
||||
Loading…
Reference in new issue