From 33d0b9cda8890d257eb0f96f7b07cabdda714c22 Mon Sep 17 00:00:00 2001 From: braks <78412429+bcakmakoglu@users.noreply.github.com> Date: Fri, 29 Jul 2022 23:03:09 +0200 Subject: [PATCH] feat(gui-v2): add option to use global api instance in `useApi` --- packages/nc-gui-v2/composables/useApi/index.ts | 17 ++++++++++++----- packages/nc-gui-v2/composables/useApi/types.ts | 1 + 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/packages/nc-gui-v2/composables/useApi/index.ts b/packages/nc-gui-v2/composables/useApi/index.ts index 6401d5a82f..3c79258684 100644 --- a/packages/nc-gui-v2/composables/useApi/index.ts +++ b/packages/nc-gui-v2/composables/useApi/index.ts @@ -3,7 +3,7 @@ import { Api } from 'nocodb-sdk' import type { Ref } from 'vue' import { addAxiosInterceptors } from './interceptors' import type { CreateApiOptions, UseApiProps, UseApiReturn } from './types' -import { createEventHook, ref, unref, useCounter, useGlobal } from '#imports' +import { createEventHook, ref, unref, useCounter, useGlobal, useNuxtApp } from '#imports' export function createApiInstance(options: CreateApiOptions = {}): Api { return addAxiosInterceptors( @@ -28,7 +28,11 @@ export function createApiInstance(options: CreateApiOpti * const { token } = await api.auth.signIn(form) * } */ -export function useApi(props: UseApiProps = {}): UseApiReturn { +export function useApi({ + useGlobalInstance = false, + apiOptions, + axiosConfig, +}: UseApiProps = {}): UseApiReturn { const state = useGlobal() /** @@ -50,8 +54,11 @@ export function useApi(props: UseApiProps const responseHook = createEventHook>() - /** fresh api instance - with interceptors for token refresh already bound */ - const api = createApiInstance(props.apiOptions) + /** global api instance */ + const $api = useNuxtApp().$api + + /** api instance - with interceptors for token refresh already bound */ + const api = useGlobalInstance && !!$api ? $api : createApiInstance(apiOptions) /** set loading to true and increment local and global request counter */ function onRequestStart() { @@ -96,7 +103,7 @@ export function useApi(props: UseApiProps return { ...config, - ...unref(props), + ...unref(axiosConfig), } }, (requestError) => { diff --git a/packages/nc-gui-v2/composables/useApi/types.ts b/packages/nc-gui-v2/composables/useApi/types.ts index 2d1a04f0c3..68637404a4 100644 --- a/packages/nc-gui-v2/composables/useApi/types.ts +++ b/packages/nc-gui-v2/composables/useApi/types.ts @@ -22,4 +22,5 @@ export interface UseApiProps { axiosConfig?: MaybeRef> /** {@link Api} options */ apiOptions?: CreateApiOptions + useGlobalInstance?: boolean }