This commit is contained in:
2025-06-24 14:14:40 +02:00
parent a000f966eb
commit 7cc292296b
8 changed files with 171 additions and 115 deletions

View File

@ -1,7 +1,7 @@
import { ofetch } from "ofetch";
export interface RequestOptions<T> extends RequestInit {
onErrorOccured?: (error: Error, statusCode: number) => void;
onErrorOccured?: (error: Error, statusCode: number) => Promise<void>;
onSuccess?: (data: T, statusCode: number) => void;
onStart?: () => void;
}
@ -21,7 +21,10 @@ 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 > => {
export const useMyFetch = async <T>(
url: string,
options?: RequestOptions<T>
): Promise<T> => {
if (options?.onStart) options.onStart();
let response = null;
try {
@ -32,7 +35,8 @@ export const useMyFetch = async <T>(url: string, options?: RequestOptions<T>): P
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;
}
@ -52,7 +56,7 @@ export const useMyFetch = async <T>(url: string, options?: RequestOptions<T>): P
// handle success to be able clearly marked that request has finished
if (response.ok && typeof options.onSuccess == "function") {
options.onSuccess( response._data, response.status);
options.onSuccess(response._data, response.status);
}
return response._data as T;