Browse Source

feat(gui-v2): add `useApi` composable

# What's changed?

* useApi provides a loading, error and response ref
* also provides event cb for error and response
pull/2892/head
braks 2 years ago
parent
commit
e9ba536c7d
  1. 4
      packages/nc-gui-v2/components/dlg/ViewCreate.vue
  2. 63
      packages/nc-gui-v2/composables/useApi.ts
  3. 5
      packages/nc-gui-v2/tsconfig.json

4
packages/nc-gui-v2/components/dlg/ViewCreate.vue

@ -99,9 +99,7 @@ function init() {
async function onSubmit() {
const isValid = await formValidator?.validateFields()
if (!isValid) return
if (form.type) {
if (isValid && form.type) {
const _meta = unref(meta)
if (!_meta || !_meta.id) return

63
packages/nc-gui-v2/composables/useApi.ts

@ -0,0 +1,63 @@
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<D = any, R = any> {
api: Api<any>
isLoading: Ref<boolean>
error: Ref<AxiosError<D, R> | null>
response: Ref<AxiosResponse<D, R> | null>
onError: EventHook<AxiosError<D, R>>['on']
onResponse: EventHook<AxiosResponse<D, R>>['on']
}
/** todo: add props? */
type UseApiProps = never
export function useApi<Data = any, RequestConfig = any>(_?: UseApiProps): UseApiReturn<Data, RequestConfig> {
const isLoading = ref(false)
const error = ref(null)
const response = ref<any>(null)
const errorHook = createEventHook<AxiosError<Data, RequestConfig>>()
const responseHook = createEventHook<AxiosResponse<Data, RequestConfig>>()
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<Data, RequestConfig>)
// 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 }
}

5
packages/nc-gui-v2/tsconfig.json

@ -12,11 +12,16 @@
"forceConsistentCasingInFileNames": true,
"types": [
"@intlify/vite-plugin-vue-i18n/client",
"vue/macro",
"vue-i18n",
"unplugin-icons/types/vue",
"nuxt-windicss"
]
},
"files": [
"nuxt-shim.d.ts",
"windi.config.ts"
],
"exclude": [
"node_modules",
"dist",

Loading…
Cancel
Save