Skip to content

Bug fix(accessControlProvider): resolve cacheTime issue for can function (#6749) #6753

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

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from 1 commit
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
164 changes: 135 additions & 29 deletions packages/core/src/hooks/accessControl/useCan/index.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,100 @@
import { useContext } from "react";
// import { useContext } from "react";

// import { getXRay } from "@refinedev/devtools-internal";
Copy link
Member

Choose a reason for hiding this comment

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

I think these commented lines were added by mistake.

Copy link
Author

Choose a reason for hiding this comment

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

yes.... skipped my mind to take 'em off. will do that in a few minutes.....

Copy link
Author

Choose a reason for hiding this comment

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

@alicanerdurmaz, the commented lines has been removed.

// import {
// type UseQueryOptions,
// type UseQueryResult,
// useQuery,
// } from "@tanstack/react-query";

// import { AccessControlContext } from "@contexts/accessControl";
// import { sanitizeResource } from "@definitions/helpers/sanitize-resource";
// import { useKeys } from "@hooks/useKeys";
// import type {
// CanParams,
// CanReturnType,
// } from "../../../contexts/accessControl/types";

// export type UseCanProps = CanParams & {
// /**
// * react-query's [useQuery](https://tanstack.com/query/v4/docs/reference/useQuery) options
// */
// queryOptions?: UseQueryOptions<CanReturnType>;
// };

// /**
// * `useCan` uses the `can` as the query function for `react-query`'s {@link https://react-query.tanstack.com/guides/queries `useQuery`}. It takes the parameters that `can` takes. It can also be configured with `queryOptions` for `useQuery`. Returns the result of `useQuery`.
// * @see {@link https://refine.dev/docs/api-reference/core/hooks/accessControl/useCan} for more details.
// *
// * @typeParam CanParams {@link https://refine.dev/docs/core/interfaceReferences#canparams}
// * @typeParam CanReturnType {@link https://refine.dev/docs/core/interfaceReferences#canreturntype}
// *
// */
// export const useCan = ({
// action,
// resource,
// params,
// queryOptions: hookQueryOptions,
// }: UseCanProps): UseQueryResult<CanReturnType> => {
// const { can, options: globalOptions } = useContext(AccessControlContext);
// const { keys, preferLegacyKeys } = useKeys();

// const { queryOptions: globalQueryOptions } = globalOptions || {};

// const mergedQueryOptions = {
// ...globalQueryOptions,
// ...hookQueryOptions,
// };

// /**
// * Since `react-query` stringifies the query keys, it will throw an error for a circular dependency if we include `React.ReactNode` elements inside the keys.
// * The feature in #2220(https://github.com/refinedev/refine/issues/2220) includes such change and to fix this, we need to remove `icon` property in the `resource`
// */
// const { resource: _resource, ...paramsRest } = params ?? {};

// const sanitizedResource = sanitizeResource(_resource);

// const queryResponse = useQuery<CanReturnType>({
// queryKey: keys()
// .access()
// .resource(resource)
// .action(action)
// .params({
// params: { ...paramsRest, resource: sanitizedResource },
// enabled: mergedQueryOptions?.enabled,
// })
// .get(preferLegacyKeys),
// // Enabled check for `can` is enough to be sure that it's defined in the query function but TS is not smart enough to know that.
// queryFn: () =>
// can?.({
// action,
// resource,
// params: { ...paramsRest, resource: sanitizedResource },
// }) ?? Promise.resolve({ can: true }),
// enabled: typeof can !== "undefined",
// ...mergedQueryOptions,
// meta: {
// ...mergedQueryOptions?.meta,
// ...getXRay("useCan", preferLegacyKeys, resource, [
// "useButtonCanAccess",
// "useNavigationButton",
// ]),
// },
// retry: false,
// });

// return typeof can === "undefined"
// ? ({ data: { can: true } } as typeof queryResponse)
// : queryResponse;
// };

import { useContext, useRef } from "react";
import { getXRay } from "@refinedev/devtools-internal";
import {
type UseQueryOptions,
type UseQueryResult,
useQuery,
} from "@tanstack/react-query";

import { AccessControlContext } from "@contexts/accessControl";
import { sanitizeResource } from "@definitions/helpers/sanitize-resource";
import { useKeys } from "@hooks/useKeys";
Expand All @@ -23,8 +111,13 @@ export type UseCanProps = CanParams & {
};

/**
* `useCan` uses the `can` as the query function for `react-query`'s {@link https://react-query.tanstack.com/guides/queries `useQuery`}. It takes the parameters that `can` takes. It can also be configured with `queryOptions` for `useQuery`. Returns the result of `useQuery`.
* @see {@link https://refine.dev/docs/api-reference/core/hooks/accessControl/useCan} for more details.
* Custom cache for `can` function results to optimize performance.
*/
const canCache = new Map<string, { result: CanReturnType; timestamp: number }>();
Copy link
Member

Choose a reason for hiding this comment

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

I don’t think we need a custom cache here. TanStack Query already has an excellent caching mechanism.


/**
* `useCan` uses the `can` as the query function for `react-query`'s {@link https://react-query.tanstack.com/guides/queries `useQuery`}.
* It now includes a custom cache for `can` results to optimize performance by reducing repeated calls.
*
* @typeParam CanParams {@link https://refine.dev/docs/core/interfaceReferences#canparams}
* @typeParam CanReturnType {@link https://refine.dev/docs/core/interfaceReferences#canreturntype}
Expand All @@ -39,22 +132,39 @@ export const useCan = ({
const { can, options: globalOptions } = useContext(AccessControlContext);
const { keys, preferLegacyKeys } = useKeys();

const { queryOptions: globalQueryOptions } = globalOptions || {};

const mergedQueryOptions = {
...globalQueryOptions,
...hookQueryOptions,
const mergedQueryOptions: UseQueryOptions<CanReturnType> = {
...(globalOptions?.queryOptions ?? {}),
...(hookQueryOptions ?? {}),
enabled:
hookQueryOptions?.enabled ??
globalOptions?.queryOptions?.enabled ??
typeof can !== "undefined",
meta: {
...(globalOptions?.queryOptions?.meta ?? {}),
...(hookQueryOptions?.meta ?? {}),
...getXRay("useCan", preferLegacyKeys, resource, [
"useButtonCanAccess",
"useNavigationButton",
]),
},
retry: false,
};

/**
* Since `react-query` stringifies the query keys, it will throw an error for a circular dependency if we include `React.ReactNode` elements inside the keys.
* The feature in #2220(https://github.com/refinedev/refine/issues/2220) includes such change and to fix this, we need to remove `icon` property in the `resource`
*/
const { resource: _resource, ...paramsRest } = params ?? {};

const sanitizedResource = sanitizeResource(_resource);

// Custom caching logic
const cacheKey = `${resource}-${action}-${JSON.stringify(paramsRest)}`;
const cacheDuration = mergedQueryOptions?.staleTime || 5 * 60 * 1000; // Default to 5 minutes
const cacheEntry = canCache.get(cacheKey);

// Check if we have a cached value and if it's still valid
if (cacheEntry && Date.now() - cacheEntry.timestamp < cacheDuration) {
return { data: cacheEntry.result } as UseQueryResult<CanReturnType>;
}

const queryResponse = useQuery<CanReturnType>({
...mergedQueryOptions,
Comment on lines +71 to +77
Copy link
Member

Choose a reason for hiding this comment

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

you must call hooks unconditionally https://react.dev/reference/rules/rules-of-hooks or it will

Thank you for helping to develop Refine, but we’d appreciate it if you could open the PR only after you’ve tested it. If you try running the access-control-casbin example you’ll see this error and the project won’t work:

Uncaught Error: Rendered fewer hooks than expected. This may be caused by an accidental early return statement.
    at renderWithHooks (chunk-WBKLWWXU.js?v=52d2936b:11623:19)
    at updateFunctionComponent (chunk-WBKLWWXU.js?v=52d2936b:14610:28)
    at beginWork (chunk-WBKLWWXU.js?v=52d2936b:15952:22)
    at beginWork$1 (chunk-WBKLWWXU.js?v=52d2936b:19789:22)
    at performUnitOfWork (chunk-WBKLWWXU.js?v=52d2936b:19234:20)
    at workLoopSync (chunk-WBKLWWXU.js?v=52d2936b:19173:13)
    at renderRootSync (chunk-WBKLWWXU.js?v=52d2936b:19152:15)
    at recoverFromConcurrentError (chunk-WBKLWWXU.js?v=52d2936b:18772:28)
    at performSyncWorkOnRoot (chunk-WBKLWWXU.js?v=52d2936b:18915:28)
    at flushSyncCallbacks (chunk-WBKLWWXU.js?v=52d2936b:9143:30)

queryKey: keys()
.access()
.resource(resource)
Expand All @@ -64,26 +174,22 @@ export const useCan = ({
enabled: mergedQueryOptions?.enabled,
})
.get(preferLegacyKeys),
// Enabled check for `can` is enough to be sure that it's defined in the query function but TS is not smart enough to know that.
queryFn: () =>
can?.({
queryFn: async () => {
const result = await (can?.({
action,
resource,
params: { ...paramsRest, resource: sanitizedResource },
}) ?? Promise.resolve({ can: true }),
enabled: typeof can !== "undefined",
...mergedQueryOptions,
meta: {
...mergedQueryOptions?.meta,
...getXRay("useCan", preferLegacyKeys, resource, [
"useButtonCanAccess",
"useNavigationButton",
]),
}) ?? Promise.resolve({ can: true }));

// Cache the result for future use
canCache.set(cacheKey, { result, timestamp: Date.now() });

return result;
},
enabled: typeof can !== "undefined",
meta: mergedQueryOptions.meta,
retry: false,
});

return typeof can === "undefined"
? ({ data: { can: true } } as typeof queryResponse)
: queryResponse;
return queryResponse;
};