Browse Source

chore(gui-v2): inject useGlobal into nuxtApp

pull/2877/head
braks 2 years ago
parent
commit
82786c6802
  1. 25
      packages/nc-gui-v2/composables/useGlobal/index.ts
  2. 4
      packages/nc-gui-v2/middleware/auth.global.ts
  3. 4
      packages/nc-gui-v2/plugins/state.ts

25
packages/nc-gui-v2/composables/useGlobal/index.ts

@ -24,29 +24,34 @@ export const useGlobal = (): UseGlobalReturn => {
const { $state, provide } = useNuxtApp()
/** If state already exists, return it */
if ($state) return $state
if (typeof $state !== 'undefined') return $state
const state = $(useGlobalState())
const state = useGlobalState()
const getters = useGlobalGetters($$(state))
const getters = useGlobalGetters(state)
const actions = useGlobalActions($$(state))
const actions = useGlobalActions(state)
/** try to refresh token before expiry (5 min before expiry) */
watch(
() => !!(state.jwtPayload && state.jwtPayload.exp && state.jwtPayload.exp - 5 * 60 < state.timestamp / 1000),
() =>
!!(
state.jwtPayload.value &&
state.jwtPayload.value.exp &&
state.jwtPayload.value.exp - 5 * 60 < state.timestamp.value / 1000
),
async (expiring) => {
if (getters.signedIn.value && state.jwtPayload && expiring) {
if (getters.signedIn.value && state.jwtPayload.value && expiring) {
await actions.refreshToken()
}
},
{ immediate: true },
)
/** provide a fresh state instance into nuxt app */
provide('state', state)
const globalState = { ...state, ...getters, ...actions } as UseGlobalReturn
console.log('provided state')
/** provide a fresh state instance into nuxt app */
provide('state', globalState)
return { ...toRefs($$(state)), ...getters, ...actions }
return globalState
}

4
packages/nc-gui-v2/middleware/auth.global.ts

@ -22,10 +22,6 @@ import { defineNuxtRouteMiddleware, navigateTo, useNuxtApp } from '#app'
export default defineNuxtRouteMiddleware((to, from) => {
const { $state } = useNuxtApp()
if (!$state) return navigateTo('/')
console.log($state)
/** if auth is required or unspecified (same as required) and user is not signed in, redirect to signin page */
if ((to.meta.requiresAuth || typeof to.meta.requiresAuth === 'undefined') && !$state.signedIn.value) {
return navigateTo('/signin')

4
packages/nc-gui-v2/plugins/state.ts

@ -17,8 +17,6 @@ import { useBreakpoints, useDark, useGlobal, watch } from '#imports'
export default defineNuxtPlugin((nuxtApp) => {
const state = useGlobal()
console.log('state', state)
const darkMode = useDark()
/** get current breakpoints (for enabling sidebar) */
@ -38,6 +36,4 @@ export default defineNuxtPlugin((nuxtApp) => {
/** is initial sidebar open */
state.sidebarOpen.value = state.signedIn.value && breakpoints.greater('md').value
nuxtApp.provide('state', state)
})

Loading…
Cancel
Save