import type { InternalApi } from 'nitropack'; import type { WatchSource } from 'vue'; type NitroFetchRequest = Exclude | (string & {}); export type CustomFetchOptions = { watchProps?: WatchSource[], lazy?: boolean, method?: string, getBody?: () => Record } type OnResponseCallback = (data: Ref) => any export function useCustomFetch(url: NitroFetchRequest, getHeaders: () => Record, options?: CustomFetchOptions) { const pending = ref(false); const data = ref(); const error = ref(); let onResponseCallback: OnResponseCallback = () => { } const onResponse = (callback: OnResponseCallback) => { onResponseCallback = callback; } const execute = async () => { pending.value = true; error.value = undefined; try { data.value = await $fetch(url, { headers: getHeaders(), method: (options?.method || 'GET') as any, body: options?.getBody ? JSON.stringify(options.getBody()) : undefined }); onResponseCallback(data); } catch (err) { error.value = err as Error; } finally { pending.value = false; } } if (options?.lazy !== true) { execute(); } if (options?.watchProps) { watch(options.watchProps, () => { execute(); }); } const refresh = execute; return { pending, execute, data, error, refresh, onResponse }; }