-
Notifications
You must be signed in to change notification settings - Fork 40
feat(use-pagination-query): create useScopedPaginationQuery composable and pagination flag to useServiceQueryKey
#5897
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
0398546
feat(scoped-infinite-query): create useScopedInfiniteQuery composable
piggggggggy a0b9a2c
fix(service-query-key): add pagination flag to useServiceQueryKey com…
piggggggggy 32909b0
feat(use-pagination-query): create usePaginationQuery composable for …
piggggggggy 6f04e62
chore: add pagination segment
piggggggggy File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
138 changes: 138 additions & 0 deletions
138
apps/web/src/query/composables/use-scoped-infinite-query.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,138 @@ | ||
| /** | ||
| * useScopedInfiniteQuery - A custom wrapper around `useInfiniteQuery` to enforce scope-based API fetching. | ||
| * | ||
| * ## Why this hook exists? | ||
| * This hook was created to integrate **scope-based API access control** with Vue Query. | ||
| * It ensures that queries are only executed when the user's granted scope matches the required scope. | ||
| * Additionally, it automatically handles loading states and prevents unnecessary queries. | ||
| * | ||
| * ## Functionality | ||
| * - Extends `useInfiniteQuery` with **grant scope validation**. | ||
| * - Runs queries only when **the user's scope is valid** and the app is **ready**. | ||
| * - Uses Vue's **reactivity** to dynamically compute the `enabled` state. | ||
| * - Supports both **static and reactive `enabled` values**. | ||
| * | ||
| * ## Parameters: | ||
| * - `options`: Standard **Vue Query options** (`UseInfiniteQueryOptions`). | ||
| * - `requiredScopes`: A list of **required grant scopes** to determine if the query should execute. | ||
| * | ||
| * ## Example: | ||
| * const query = useScopedInfiniteQuery( | ||
| * { | ||
| * queryKey: ['dashboard', dashboardId], | ||
| * queryFn: () => fetchDashboardData(dashboardId), | ||
| * initialPageParam: 1, | ||
| * getNextPageParam: (lastPage, allPages) => {} | ||
| * enabled: computed(() => isUserAuthorized.value), | ||
| * }, | ||
| * ['DOMAIN', 'WORKSPACE'] | ||
| * ); | ||
| */ | ||
|
|
||
| import type { MaybeRef } from '@vueuse/core'; | ||
| import { toValue } from '@vueuse/core'; | ||
| import { computed, type ComputedRef } from 'vue'; | ||
|
|
||
| import type { | ||
| InfiniteData, | ||
| QueryKey, | ||
| } from '@tanstack/vue-query'; | ||
| import { | ||
| useInfiniteQuery, type UseInfiniteQueryOptions, type UseInfiniteQueryReturnType, | ||
| } from '@tanstack/vue-query'; | ||
|
|
||
| import type { GrantScope } from '@/api-clients/identity/token/schema/type'; | ||
| import type { QueryKeyArray } from '@/query/query-key/_types/query-key-type'; | ||
|
|
||
| import { useAppContextStore } from '@/store/app-context/app-context-store'; | ||
| import { useAuthorizationStore } from '@/store/authorization/authorization-store'; | ||
|
|
||
|
|
||
| type ScopedEnabled = MaybeRef<boolean>; | ||
|
|
||
|
|
||
| export const useScopedInfiniteQuery = <TQueryFnData, TError = unknown, TData = InfiniteData<TQueryFnData>, TQueryKey extends QueryKey = QueryKey, TPageParam = unknown>( | ||
| options: UseInfiniteQueryOptions<TQueryFnData, TError, TData, TQueryFnData, TQueryKey, TPageParam>, | ||
| requiredScopes: [GrantScope, ...GrantScope[]], | ||
| ): UseInfiniteQueryReturnType<TData, TError> => { | ||
| // [Dev Warning] This query is missing `requiredScopes`. | ||
| // All scoped queries must explicitly define at least one valid scope for clarity and safety. | ||
| if (import.meta.env.DEV && (!requiredScopes || requiredScopes.length === 0)) { | ||
| _warnOncePerTick(() => { | ||
| console.warn('[useScopedInfiniteQuery] `requiredScopes` is missing or empty.', { | ||
| queryKey: _extractQueryKey((options as any).queryKey), | ||
| suggestion: 'Pass at least one valid scope like [\'DOMAIN\'], [\'WORKSPACE\'], etc.', | ||
| }); | ||
| return true; | ||
| }); | ||
| } | ||
|
|
||
| const appContextStore = useAppContextStore(); | ||
| const authorizationStore = useAuthorizationStore(); | ||
|
|
||
| const currentGrantScope = computed<GrantScope | undefined>( | ||
| () => authorizationStore.state.currentGrantInfo?.scope, | ||
| ); | ||
| const isAppReady = computed(() => !appContextStore.getters.globalGrantLoading); | ||
|
|
||
| const isValidScope = computed(() => currentGrantScope.value !== undefined | ||
| && requiredScopes.includes(currentGrantScope.value)); | ||
|
|
||
| const rawEnabled = (options as { enabled?: ScopedEnabled }).enabled; | ||
| const queryEnabled = computed(() => { | ||
| const inheritedEnabled = rawEnabled !== undefined ? toValue(rawEnabled) : true; | ||
| return inheritedEnabled && isValidScope.value && isAppReady.value; | ||
| }); | ||
|
|
||
| // [Dev Warning] The current user's scope is not included in the allowed `requiredScopes`. | ||
| // This usually indicates a configuration mistake in the query declaration. | ||
| if (import.meta.env.DEV) { | ||
| const currentScope = currentGrantScope.value; | ||
| if (isAppReady.value && currentScope && toValue(rawEnabled) && !requiredScopes.includes(currentScope)) { | ||
| _warnOncePerTick(() => { | ||
| console.warn('[useScopedInfiniteQuery] Invalid requiredScopes for current scope:', { | ||
| queryKey: _extractQueryKey((options as any).queryKey), | ||
| requiredScopes, | ||
| currentScope, | ||
| }); | ||
| return true; | ||
| }); | ||
| } | ||
| } | ||
|
|
||
| return useInfiniteQuery<TQueryFnData, TError, TData, TQueryKey, TPageParam>({ | ||
| ...options, | ||
| enabled: queryEnabled, | ||
| }); | ||
| }; | ||
|
|
||
| const _extractQueryKey = (input: unknown): QueryKeyArray => toValue(input as ComputedRef<QueryKeyArray>); | ||
|
|
||
|
|
||
|
|
||
| /* Warning Logger Utilities */ | ||
| const _warnedKeys = new Set<string>(); | ||
| const _getCallerKey = (): string => { | ||
| try { | ||
| const err = new Error(); | ||
| const stack = err.stack?.split('\n') || []; | ||
|
|
||
| const caller = stack.find((line, i) => i > 1 | ||
| && (line.includes('.ts') || line.includes('.vue')) | ||
| && !line.includes('use-scoped-infinite-query')); | ||
|
|
||
| return caller?.trim() ?? 'UNKNOWN_CALLSITE'; | ||
| } catch { | ||
| return 'UNKNOWN_CALLSITE'; | ||
| } | ||
| }; | ||
| const _warnOncePerTick = (log: () => boolean) => { | ||
| const key = _getCallerKey(); | ||
| if (_warnedKeys.has(key)) return; | ||
| const didLog = log(); | ||
|
|
||
| if (didLog) { | ||
| _warnedKeys.add(key); | ||
| queueMicrotask(() => _warnedKeys.delete(key)); | ||
| } | ||
| }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,65 @@ | ||
| import type { Query } from '@cloudforet/core-lib/space-connector/type'; | ||
|
|
||
| import type { Page } from '@/api-clients/_common/schema/type'; | ||
|
|
||
| type LoadParams = Record<string, unknown> & { | ||
| page?: Page; | ||
| }; | ||
|
|
||
|
|
||
| export const omitPageFromLoadParams = <T extends LoadParams>(params: T): Omit<T, 'page'> => { | ||
| const copiedParams = { ...params }; | ||
| delete copiedParams.page; | ||
| return copiedParams; | ||
| }; | ||
|
|
||
| type QueryParams = Record<string, unknown> & { | ||
| query?: Query; | ||
| }; | ||
|
|
||
| export const omitPageQueryParams = (params: QueryParams) => { | ||
| const copiedQuery = params.query ? { ...params.query } : undefined; | ||
| if (copiedQuery) delete copiedQuery.page; | ||
|
|
||
| return { | ||
| ...params, | ||
| query: copiedQuery, | ||
| }; | ||
| }; | ||
|
|
||
| const _addPageToLoadParams = ( | ||
| params: LoadParams, | ||
| page: Page, | ||
| ): LoadParams => ({ | ||
| ...params, | ||
| page, | ||
| }); | ||
|
|
||
| const _addPageToListParams = ( | ||
| params: QueryParams, | ||
| page: Page, | ||
| ): QueryParams => ({ | ||
| ...params, | ||
| query: { | ||
| ...(params.query ?? {}), | ||
| page, | ||
| }, | ||
| }); | ||
|
|
||
| export const addPageToVerbParams = <TParams extends object>( | ||
| verb: 'load' | 'list' | 'analyze' | 'stat', | ||
| params: TParams, | ||
| page: Page, | ||
| ): TParams => { | ||
| switch (verb) { | ||
| case 'load': | ||
| return _addPageToLoadParams(params as LoadParams, page) as TParams; | ||
| case 'list': | ||
| case 'analyze': | ||
| case 'stat': | ||
| return _addPageToListParams(params as QueryParams, page) as TParams; | ||
| default: | ||
| console.warn(`[addPageToVerbParams] Unsupported verb: ${verb}`); | ||
| return params; | ||
| } | ||
| }; | ||
121 changes: 121 additions & 0 deletions
121
apps/web/src/query/pagination/use-scoped-pagination-query.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| @@ -0,0 +1,121 @@ | ||||||||||||
| import type { ComputedRef } from 'vue'; | ||||||||||||
| import { | ||||||||||||
| computed, watch, | ||||||||||||
| } from 'vue'; | ||||||||||||
|
|
||||||||||||
| import type { InfiniteData } from '@tanstack/vue-query'; | ||||||||||||
| import { type UseInfiniteQueryOptions } from '@tanstack/vue-query'; | ||||||||||||
|
|
||||||||||||
| import type { GrantScope } from '@/api-clients/identity/token/schema/type'; | ||||||||||||
| import { useScopedInfiniteQuery } from '@/query/composables/use-scoped-infinite-query'; | ||||||||||||
| import { addPageToVerbParams } from '@/query/pagination/pagination-query-helper'; | ||||||||||||
| import type { QueryKeyArray } from '@/query/query-key/_types/query-key-type'; | ||||||||||||
|
|
||||||||||||
|
|
||||||||||||
| /** | ||||||||||||
| * useScopedPaginationQuery | ||||||||||||
| * | ||||||||||||
| * A wrapper around `useInfiniteQuery` for paginated resource fetching with consistent queryKey and page parameter handling. | ||||||||||||
| * Automatically appends page params (start, limit) to the query function based on the API verb structure. | ||||||||||||
| * Supports dynamic fetching of missing pages based on the `thisPage` value. | ||||||||||||
| * | ||||||||||||
| * @template TParams - API parameter type (excluding page info) | ||||||||||||
| * @template TPageData - Response data type, must include `results` and `total_count` | ||||||||||||
| * @template TError - Optional error type | ||||||||||||
| * | ||||||||||||
| * @param options - Query config including: | ||||||||||||
| * - queryFn: the fetcher function (expects page-added params) | ||||||||||||
| * - params: the base API params (as a ComputedRef) | ||||||||||||
| * - initialPageParam: (optional) starting page index, default is 1 | ||||||||||||
| * - ...restOptions: all other `useInfiniteQuery` options (except those overridden) | ||||||||||||
| * | ||||||||||||
| * @param pageOptions - Pagination control: | ||||||||||||
| * - thisPage: current page number (1-based) | ||||||||||||
| * - pageSize: number of items per page | ||||||||||||
| * - verb: one of 'list' | 'stat' | 'analyze' | 'load' (used to insert page info in correct param structure) | ||||||||||||
| * | ||||||||||||
| * @param requiredScopes - A list of **required grant scopes** to determine if the query should execute. | ||||||||||||
| * | ||||||||||||
| * | ||||||||||||
| * @returns { | ||||||||||||
| * data: ComputedRef<TPageData | undefined> - Data for the current page (1-based index) | ||||||||||||
| * totalCount: ComputedRef<number> - Total number of items (from first page) | ||||||||||||
| * isReady: ComputedRef<boolean> - Whether the current page is loaded | ||||||||||||
| * isLoading: ComputedRef<boolean> - Whether the current page is being fetched | ||||||||||||
| * query: Return value of useScopedInfiniteQuery - includes all raw query states | ||||||||||||
| * } | ||||||||||||
| */ | ||||||||||||
|
|
||||||||||||
| type PaginatableBaseData = { | ||||||||||||
| results?: any[]; | ||||||||||||
| total_count?: number; | ||||||||||||
| }; | ||||||||||||
|
|
||||||||||||
| type UsePaginationQueryOptions<TParams extends object, TPageData, TError> = Omit< | ||||||||||||
| UseInfiniteQueryOptions<TPageData, TError, InfiniteData<TPageData>, TPageData, QueryKeyArray, number>, | ||||||||||||
| 'initialPageParam' | 'queryFn' | 'getNextPageParam' | ||||||||||||
| > & { | ||||||||||||
| queryFn: (params: TParams) => Promise<TPageData>; | ||||||||||||
| params: ComputedRef<TParams>; | ||||||||||||
| initialPageParam?: number; | ||||||||||||
| }; | ||||||||||||
|
|
||||||||||||
| interface UsePaginationQueryPageOptions { | ||||||||||||
| thisPage: ComputedRef<number>; | ||||||||||||
| pageSize: ComputedRef<number>; | ||||||||||||
| verb: 'list' | 'stat' | 'analyze' | 'load'; | ||||||||||||
| } | ||||||||||||
|
|
||||||||||||
| export const useScopedPaginationQuery = <TParams extends object, TPageData extends PaginatableBaseData, TError = unknown>( | ||||||||||||
| options: UsePaginationQueryOptions<TParams, TPageData, TError>, | ||||||||||||
| pageOptions: UsePaginationQueryPageOptions, | ||||||||||||
| requiredScopes: [GrantScope, ...GrantScope[]], | ||||||||||||
| ) => { | ||||||||||||
| const { thisPage, pageSize, verb } = pageOptions; | ||||||||||||
| const { | ||||||||||||
| queryFn, params, initialPageParam = 1, ...restOptions | ||||||||||||
| } = options; | ||||||||||||
|
|
||||||||||||
|
|
||||||||||||
| // Wraps the queryFn to inject pagination params (start, limit) into correct structure based on verb. | ||||||||||||
| // For example: | ||||||||||||
| // - 'load': params.page = { start, limit } | ||||||||||||
| // - 'list': params.query.page = { start, limit } | ||||||||||||
| const wrappedQueryFn = ({ pageParam }: { pageParam: number }) => queryFn(addPageToVerbParams(verb, params.value, { | ||||||||||||
| start: pageParam, | ||||||||||||
| limit: pageSize.value, | ||||||||||||
| })); | ||||||||||||
|
|
||||||||||||
|
|
||||||||||||
| const query = useScopedInfiniteQuery<TPageData, TError, InfiniteData<TPageData>, QueryKeyArray, number>({ | ||||||||||||
| ...restOptions, | ||||||||||||
| queryFn: wrappedQueryFn, | ||||||||||||
| initialPageParam, | ||||||||||||
| getNextPageParam: (lastPage, allPages) => { | ||||||||||||
| const loadedCount = allPages.reduce((acc, page) => acc + (page?.results?.length || 0), 0); | ||||||||||||
| return loadedCount < (lastPage?.total_count || 0) ? loadedCount + 1 : undefined; | ||||||||||||
| }, | ||||||||||||
| // getPreviousPageParam: (firstPage, allPages) => { | ||||||||||||
| // const prevStart = allPages[0]?.results?.length ?? 0; | ||||||||||||
| // return prevStart > 1 ? Math.max(1, prevStart - pageSize.value) : undefined; | ||||||||||||
| // }, | ||||||||||||
| }, requiredScopes); | ||||||||||||
|
|
||||||||||||
| // Watches the `thisPage` ref and automatically fetches all pages up to that index | ||||||||||||
| // Ensures that the page requested by the consumer is available in the data list | ||||||||||||
| watch(thisPage, async (val) => { | ||||||||||||
| const currentLength = query.data.value?.pages?.length ?? 0; | ||||||||||||
| if (val > currentLength && !query.isFetchingNextPage.value) { | ||||||||||||
| const calls = Array.from({ length: val - currentLength }); | ||||||||||||
| await Promise.all(calls.map(() => query.fetchNextPage())); | ||||||||||||
|
Comment on lines
+109
to
+110
|
||||||||||||
| const calls = Array.from({ length: val - currentLength }); | |
| await Promise.all(calls.map(() => query.fetchNextPage())); | |
| for (let i = currentLength; i < val; i++) { | |
| await query.fetchNextPage(); | |
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
When
params.queryis undefined, this helper still adds aquery: undefinedfield, altering object shape. Consider returningparamsunchanged in that case to preserve the original structure.