permission-react: use object instead of tuple for usePermission args

Co-authored-by: Mike Lewis <mtlewis@users.noreply.github.com>
Signed-off-by: Joe Porpeglia <josephp@spotify.com>
This commit is contained in:
Joe Porpeglia
2022-03-16 17:14:07 -04:00
committed by Joe Porpeglia
parent d88b5b3009
commit 91703e8086
4 changed files with 23 additions and 12 deletions
@@ -48,10 +48,10 @@ export function useEntityPermission(
allowed,
loading: loadingPermission,
error: permissionError,
} = usePermission(
} = usePermission({
permission,
entity ? stringifyEntityRef(entity) : undefined,
);
resourceRef: entity ? stringifyEntityRef(entity) : undefined,
});
if (loadingEntity || loadingPermission) {
return { loading: true, allowed: false };
@@ -47,9 +47,9 @@ export const PermissionedRoute = (
const { permission, resourceRef, errorComponent, ...otherProps } = props;
const permissionResult = usePermission(
...(isResourcePermission(permission)
? [permission, resourceRef]
: [permission]),
isResourcePermission(permission)
? { permission, resourceRef }
: { permission },
);
const app = useApp();
const { NotFoundErrorPage } = app.getComponents();
@@ -32,6 +32,17 @@ export type AsyncPermissionResult = {
error?: Error;
};
/** @public */
export type UsePermissionProps =
| {
permission: Exclude<Permission, ResourcePermission>;
resourceRef?: never;
}
| {
permission: ResourcePermission;
resourceRef: string | undefined;
};
/**
* React hook utility for authorization. Given either a non-resource
* {@link @backstage/plugin-permission-common#Permission} or a
@@ -41,7 +52,7 @@ export type AsyncPermissionResult = {
* {@link @backstage/plugin-permission-common/PermissionClient#authorize} for
* more details.
*
* The resourceRef parameter is optional to allow calling this hook with an
* The resourceRef field is optional to allow calling this hook with an
* entity that might be loading asynchronously, but when resourceRef is not
* supplied, the value of `allowed` will always be false.
*
@@ -51,12 +62,10 @@ export type AsyncPermissionResult = {
* @public
*/
export function usePermission(
...[permission, resourceRef]:
| [ResourcePermission, string | undefined]
| [Exclude<Permission, ResourcePermission>]
props: UsePermissionProps,
): AsyncPermissionResult {
const permissionApi = useApi(permissionApiRef);
const { data, error } = useSWR({ permission, resourceRef }, async args => {
const { data, error } = useSWR(props, async (args: UsePermissionProps) => {
// We could make the resourceRef parameter required to avoid this check, but
// it would make using this hook difficult in situations where the entity
// must be asynchronously loaded, so instead we short-circuit to a deny when
@@ -63,7 +63,9 @@ export const ScaffolderPageContents = ({
},
};
const { allowed } = usePermission(catalogEntityCreatePermission);
const { allowed } = usePermission({
permission: catalogEntityCreatePermission,
});
return (
<Page themeId="home">