fix fetch

This commit is contained in:
2025-06-24 12:05:43 +02:00
parent 26e7467f7f
commit a000f966eb
14 changed files with 3326 additions and 13451 deletions

View File

@ -1,7 +1,7 @@
import { ofetch } from "ofetch";
export interface RequestOptions<T> extends RequestInit {
onError?: (error: Error, statusCode: number) => void;
onErrorOccured?: (error: Error, statusCode: number) => void;
onSuccess?: (data: T, statusCode: number) => void;
onStart?: () => void;
}
@ -21,10 +21,7 @@ export interface RequestOptions<T> extends RequestInit {
* @example
* const { data } = useMyFetch<{ name: string }>('/api/user')
*/
export const useMyFetch = async <T>(
url: string,
options?: RequestOptions<T>
): Promise<T | undefined> => {
export const useMyFetch = async <T>(url: string, options?: RequestOptions<T>): Promise<T > => {
if (options?.onStart) options.onStart();
let response = null;
try {
@ -35,8 +32,7 @@ export const useMyFetch = async <T>(
options.credentials = "include";
if (import.meta.server) {
const api_uri =
event?.node.req.headers["api-uri"] || "http://localhost:4000";
const api_uri = event?.node.req.headers["api-uri"] || "http://localhost:4000";
url = api_uri + url;
options.headers = event?.headers;
}
@ -50,23 +46,23 @@ export const useMyFetch = async <T>(
}
// handle errors if any
if (!response.ok && typeof options.onError == "function") {
options.onError(new Error(response.statusText), response.status);
if (!response.ok && typeof options.onErrorOccured == "function") {
options.onErrorOccured(new Error(response.statusText), response.status);
}
// handle success to be able clearly marked that request has finished
if (response.ok && typeof options.onSuccess == "function") {
options.onSuccess(response._data.data, response.status);
options.onSuccess( response._data, response.status);
}
return response._data as T;
} catch (e) {
// handle errors if any
if (typeof options?.onError == "function") {
options.onError(e as Error, response?.status || 500);
if (typeof options?.onErrorOccured == "function") {
options.onErrorOccured(e as Error, response?.status || 500);
} else {
console.error(e);
}
return undefined;
return {} as T;
}
};