import type { AxiosError, AxiosResponse } from 'axios' import type { Api } from 'nocodb-sdk' import type { Ref } from 'vue' import type { EventHook } from '@vueuse/core' import { createEventHook, ref, useNuxtApp } from '#imports' interface UseApiReturn { api: Api isLoading: Ref error: Ref | null> response: Ref | null> onError: EventHook>['on'] onResponse: EventHook>['on'] } /** todo: add props? */ type UseApiProps = never export function useApi(_?: UseApiProps): UseApiReturn { const isLoading = ref(false) const error = ref(null) const response = ref(null) const errorHook = createEventHook>() const responseHook = createEventHook>() const { $api } = useNuxtApp() $api.instance.interceptors.request.use( (config) => { error.value = null response.value = null isLoading.value = true return config }, (requestError) => { errorHook.trigger(requestError) error.value = requestError response.value = null isLoading.value = false }, ) $api.instance.interceptors.response.use( (apiResponse) => { responseHook.trigger(apiResponse as AxiosResponse) // can't properly typecast response.value = apiResponse isLoading.value = false }, (apiError) => { errorHook.trigger(apiError) error.value = apiError isLoading.value = false }, ) return { api: $api, isLoading, response, error, onError: errorHook.on, onResponse: responseHook.on } }