From 84b9f8b10f8315a92f8cc1346d3dc1b17a2ddab8 Mon Sep 17 00:00:00 2001 From: braks <78412429+bcakmakoglu@users.noreply.github.com> Date: Mon, 19 Sep 2022 16:04:25 +0200 Subject: [PATCH] refactor(nc-gui): use injection state for `useUIPermission` --- .../composables/useUIPermission/index.ts | 44 +++++++------------ 1 file changed, 17 insertions(+), 27 deletions(-) diff --git a/packages/nc-gui/composables/useUIPermission/index.ts b/packages/nc-gui/composables/useUIPermission/index.ts index 57249d1d95..5f06758941 100644 --- a/packages/nc-gui/composables/useUIPermission/index.ts +++ b/packages/nc-gui/composables/useUIPermission/index.ts @@ -1,33 +1,13 @@ import { isString } from '@vueuse/core' import type { Permission } from './rolePermissions' import rolePermissions from './rolePermissions' -import { USER_PROJECT_ROLES, computed, useGlobal, useState } from '#imports' -import type { ProjectRole, Role, Roles } from '~/lib' +import { useGlobal, useInjectionState, useRoles } from '#imports' +import type { ProjectRole, Role } from '~/lib' -export function useUIPermission() { - const { user, previewAs } = useGlobal() - - const projectRoles = useState>(USER_PROJECT_ROLES, () => ({})) - - const allRoles = useState('allRoles', () => - computed(() => { - let userRoles = user.value?.roles - - // if string populate key-value paired object - if (isString(userRoles)) { - userRoles = userRoles.split(',').reduce((acc, role) => { - acc[role] = true - return acc - }, {}) - } - - // merge user role and project specific user roles - return { - ...userRoles, - ...projectRoles.value, - } - }), - ) +const [setup, use] = useInjectionState(() => { + const { previewAs } = useGlobal() + + const { allRoles } = useRoles() const hasPermission = (role: Role | ProjectRole, hasRole: boolean, permission: Permission | string) => { const rolePermission = rolePermissions[role] @@ -51,5 +31,15 @@ export function useUIPermission() { ) } - return { isUIAllowed } + return { isUIAllowed, projectRoles } +}, 'useUIPermission') + +export function useUIPermission() { + let usePermissions = use() + + if (!usePermissions) { + usePermissions = setup() + } + + return { isUIAllowed: usePermissions.isUIAllowed } }