Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
138 changes: 138 additions & 0 deletions apps/web/src/query/composables/use-scoped-infinite-query.ts
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));
}
};
65 changes: 65 additions & 0 deletions apps/web/src/query/pagination/pagination-query-helper.ts
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;

Comment on lines +21 to +23
Copy link

Copilot AI May 29, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When params.query is undefined, this helper still adds a query: undefined field, altering object shape. Consider returning params unchanged in that case to preserve the original structure.

Suggested change
const copiedQuery = params.query ? { ...params.query } : undefined;
if (copiedQuery) delete copiedQuery.page;
if (!params.query) {
return params;
}
const copiedQuery = { ...params.query };
delete copiedQuery.page;

Copilot uses AI. Check for mistakes.
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 apps/web/src/query/pagination/use-scoped-pagination-query.ts
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
Copy link

Copilot AI May 29, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Concurrent calls to fetchNextPage may race and break page ordering. Consider fetching pages sequentially or chaining with for/reduce to preserve correct order.

Suggested change
const calls = Array.from({ length: val - currentLength });
await Promise.all(calls.map(() => query.fetchNextPage()));
for (let i = currentLength; i < val; i++) {
await query.fetchNextPage();
}

Copilot uses AI. Check for mistakes.
}
});

return {
data: computed(() => query.data.value?.pages?.[thisPage.value - 1]),
totalCount: computed(() => query.data.value?.pages?.[0]?.total_count ?? 0),
isReady: computed(() => !!query.data.value?.pages?.[thisPage.value - 1]),
isLoading: computed(() => !query.data.value?.pages?.[thisPage.value - 1] && query.isFetchingNextPage.value),
query,
};
};
Loading
Loading