diff --git a/dashboard/composables/useCustomFetch.ts b/dashboard/composables/useCustomFetch.ts new file mode 100644 index 0000000..405c801 --- /dev/null +++ b/dashboard/composables/useCustomFetch.ts @@ -0,0 +1,41 @@ +import type { InternalApi } from 'nitropack'; +import type { WatchSource } from 'vue'; + + +type NitroFetchRequest = Exclude | (string & {}); + +export type CustomFetchOptions = { + watchProps?: WatchSource[], + lazy?: boolean +} + +export function useCustomFetch(url: NitroFetchRequest, getHeaders: () => Record, options?: CustomFetchOptions) { + + const pending = ref(false); + const data = ref(); + const error = ref(); + + const execute = async () => { + pending.value = true; + error.value = undefined; + try { + data.value = await $fetch(url, { headers: getHeaders() }); + } catch (err) { + error.value = err as Error; + } finally { + pending.value = false; + } + } + + if (options?.lazy !== true) { + execute(); + } + + if (options?.watchProps) { + watch(options.watchProps, () => { + execute(); + }); + } + + return { pending, execute, data, error }; +} \ No newline at end of file