|
| 1 | +/** |
| 2 | + * useScopedQuery - A custom wrapper around `useQuery` to enforce scope-based API fetching. |
| 3 | + * |
| 4 | + * ## Why this hook exists? |
| 5 | + * This hook was created to integrate **scope-based API access control** with Vue Query. |
| 6 | + * It ensures that queries are only executed when the user's granted scope matches the required scope. |
| 7 | + * Additionally, it automatically handles loading states and prevents unnecessary queries. |
| 8 | + * |
| 9 | + * ## Functionality |
| 10 | + * - Extends `useQuery` with **grant scope validation**. |
| 11 | + * - Runs queries only when **the user's scope is valid** and the app is **ready**. |
| 12 | + * - Uses Vue's **reactivity** to dynamically compute the `enabled` state. |
| 13 | + * - Supports both **static and reactive `enabled` values**. |
| 14 | + * |
| 15 | + * ## Parameters: |
| 16 | + * - `options`: Standard **Vue Query options** (`UseQueryOptions`). |
| 17 | + * - `requiredScopes`: A list of **required grant scopes** to determine if the query should execute. |
| 18 | + * |
| 19 | + * ## Supported Query Options: |
| 20 | + * - `queryKey`, `queryFn`, `select`, `initialData`, `staleTime`, `enabled` (static or reactive) |
| 21 | + * |
| 22 | + * ## Example: |
| 23 | + * const query = useScopedQuery( |
| 24 | + * { |
| 25 | + * queryKey: ['dashboard', dashboardId], |
| 26 | + * queryFn: () => fetchDashboardData(dashboardId), |
| 27 | + * enabled: computed(() => isUserAuthorized.value), |
| 28 | + * }, |
| 29 | + * ['DOMAIN', 'WORKSPACE'] |
| 30 | + * ); |
| 31 | + */ |
| 32 | + |
| 33 | +import type { MaybeRef } from '@vueuse/core'; |
| 34 | +import { toValue } from '@vueuse/core'; |
| 35 | +import { computed, type ComputedRef } from 'vue'; |
| 36 | + |
| 37 | +import { |
| 38 | + useQuery, type UseQueryOptions, type UseQueryReturnType, |
| 39 | +} from '@tanstack/vue-query'; |
| 40 | + |
| 41 | +import type { GrantScope } from '@/api-clients/identity/token/schema/type'; |
| 42 | +import type { QueryKeyArray } from '@/query/query-key/_types/query-key-type'; |
| 43 | + |
| 44 | +import { useAppContextStore } from '@/store/app-context/app-context-store'; |
| 45 | +import { useUserStore } from '@/store/user/user-store'; |
| 46 | + |
| 47 | + |
| 48 | +type ScopedEnabled = MaybeRef<boolean>; |
| 49 | + |
| 50 | + |
| 51 | +export const useScopedQuery = <TQueryFnData, TError = unknown, TData = TQueryFnData>( |
| 52 | + options: UseQueryOptions<TQueryFnData, TError, TData>, |
| 53 | + requiredScopes: [GrantScope, ...GrantScope[]], |
| 54 | +): UseQueryReturnType<TData, TError> => { |
| 55 | + // [Dev Warning] This query is missing `requiredScopes`. |
| 56 | + // All scoped queries must explicitly define at least one valid scope for clarity and safety. |
| 57 | + if (import.meta.env.DEV && (!requiredScopes || requiredScopes.length === 0)) { |
| 58 | + _warnOncePerTick(() => { |
| 59 | + console.warn('[useScopedQuery] `requiredScopes` is missing or empty.', { |
| 60 | + queryKey: _extractQueryKey((options as any).queryKey), |
| 61 | + suggestion: 'Pass at least one valid scope like [\'DOMAIN\'], [\'WORKSPACE\'], etc.', |
| 62 | + }); |
| 63 | + return true; |
| 64 | + }); |
| 65 | + } |
| 66 | + |
| 67 | + const appContextStore = useAppContextStore(); |
| 68 | + const userStore = useUserStore(); |
| 69 | + |
| 70 | + const currentGrantScope = computed<GrantScope | undefined>( |
| 71 | + () => userStore.state.currentGrantInfo?.scope, |
| 72 | + ); |
| 73 | + const isAppReady = computed(() => !appContextStore.getters.globalGrantLoading); |
| 74 | + |
| 75 | + const isValidScope = computed(() => currentGrantScope.value !== undefined |
| 76 | + && requiredScopes.includes(currentGrantScope.value)); |
| 77 | + |
| 78 | + const rawEnabled = (options as { enabled?: ScopedEnabled }).enabled; |
| 79 | + const queryEnabled = computed(() => { |
| 80 | + const inheritedEnabled = rawEnabled !== undefined ? toValue(rawEnabled) : true; |
| 81 | + return inheritedEnabled && isValidScope.value && isAppReady.value; |
| 82 | + }); |
| 83 | + |
| 84 | + // [Dev Warning] The current user's scope is not included in the allowed `requiredScopes`. |
| 85 | + // This usually indicates a configuration mistake in the query declaration. |
| 86 | + if (import.meta.env.DEV) { |
| 87 | + const currentScope = currentGrantScope.value; |
| 88 | + if (isAppReady.value && currentScope && !requiredScopes.includes(currentScope)) { |
| 89 | + _warnOncePerTick(() => { |
| 90 | + console.warn('[useScopedQuery] Invalid requiredScopes for current scope:', { |
| 91 | + queryKey: _extractQueryKey((options as any).queryKey), |
| 92 | + requiredScopes, |
| 93 | + currentScope, |
| 94 | + }); |
| 95 | + return true; |
| 96 | + }); |
| 97 | + } |
| 98 | + } |
| 99 | + |
| 100 | + return useQuery<TQueryFnData, TError, TData>({ |
| 101 | + ...options, |
| 102 | + enabled: queryEnabled, |
| 103 | + }); |
| 104 | +}; |
| 105 | + |
| 106 | +const _extractQueryKey = (input: unknown): QueryKeyArray => toValue(input as ComputedRef<QueryKeyArray>); |
| 107 | + |
| 108 | + |
| 109 | + |
| 110 | +/* Warning Logger Utilities */ |
| 111 | +const _warnedKeys = new Set<string>(); |
| 112 | +const _getCallerKey = (): string => { |
| 113 | + try { |
| 114 | + const err = new Error(); |
| 115 | + const stack = err.stack?.split('\n') || []; |
| 116 | + |
| 117 | + const caller = stack.find((line, i) => i > 1 |
| 118 | + && (line.includes('.ts') || line.includes('.vue')) |
| 119 | + && !line.includes('use-scoped-query')); |
| 120 | + |
| 121 | + return caller?.trim() ?? 'UNKNOWN_CALLSITE'; |
| 122 | + } catch { |
| 123 | + return 'UNKNOWN_CALLSITE'; |
| 124 | + } |
| 125 | +}; |
| 126 | +const _warnOncePerTick = (log: () => boolean) => { |
| 127 | + const key = _getCallerKey(); |
| 128 | + if (_warnedKeys.has(key)) return; |
| 129 | + const didLog = log(); |
| 130 | + |
| 131 | + if (didLog) { |
| 132 | + _warnedKeys.add(key); |
| 133 | + queueMicrotask(() => _warnedKeys.delete(key)); |
| 134 | + } |
| 135 | +}; |
0 commit comments