From d4dc345d263ce073a8dbd885b131230c9c58e352 Mon Sep 17 00:00:00 2001 From: Abizrh Date: Sun, 10 Aug 2025 15:47:55 +0700 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat=20(composables):=20add=20xfetc?= =?UTF-8?q?h?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/composables/useXfetch.ts | 70 ++++++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 app/composables/useXfetch.ts diff --git a/app/composables/useXfetch.ts b/app/composables/useXfetch.ts new file mode 100644 index 00000000..24518c18 --- /dev/null +++ b/app/composables/useXfetch.ts @@ -0,0 +1,70 @@ +export interface XError { + code: string + message: string + expectedVal?: string + givenVal?: string +} + +export type XErrors = Record + +export interface XfetchResult { + success: boolean + status_code: number + body: object | any + errors?: XErrors | undefined + error?: XError | undefined + message?: string +} + +export type XfetchMethod = 'GET' | 'POST' | 'PATCH' | 'PUT' | 'DELETE' + +export async function xfetch( + url: string, + method: XfetchMethod = 'GET', + input?: object | FormData, + headers?: any, + _type = 'json', +): Promise { + let success = false + let body: object | any = {} + let errors: XErrors = {} + let error: XError | undefined = { + code: '', + message: '', + } + let message: string | undefined = '' + + if (!headers) { + headers = {} + } + if (input && !(input instanceof FormData)) { + headers['Content-Type'] = 'application/json' + } + + try { + const res = await $fetch.raw(url, { + method, + headers, + body: input instanceof FormData ? input : JSON.stringify(input), + }) + + body = res._data + success = true + return { success, status_code: res.status, body, errors, error, message } + } catch (fetchError: any) { + const status = fetchError.response?.status || 500 + const resJson = fetchError.data + + if (resJson?.errors) { + errors = resJson.errors + } else if (resJson?.code && resJson?.message) { + error = { code: resJson.code, message: resJson.message } + } else if (resJson?.message) { + message = resJson.message + } else { + message = fetchError.message || 'Something went wrong' + } + + return { success, status_code: status, body, errors, error, message } + } +}