Files
Tom Moor bf45e97641 chore: Enforce type import consistency (#10968)
* Update types

* fix circular dep

* type imports

* lint type imports and --fix
2025-12-19 23:07:02 -05:00

40 lines
1.1 KiB
TypeScript

import { useEffect } from "react";
import type Model from "~/models/base/Model";
import useCurrentUser from "./useCurrentUser";
import useStores from "./useStores";
/**
* Retrieve the abilities of a policy for a given entity, if the policy is not
* located in the store, it will be fetched from the server.
*
* @param entity The model or model id
* @returns The policy for the model
*/
export default function usePolicy(entity?: string | Model | null) {
const { policies } = useStores();
const user = useCurrentUser({ rejectOnEmpty: false });
const entityId = entity
? typeof entity === "string"
? entity
: entity.id
: "";
const policy = policies.get(entityId);
useEffect(() => {
if (
entity &&
typeof entity !== "string" &&
!entity.isNew &&
!entity.isSaving
) {
// The policy for this model is missing and we have an authenticated session, attempt to
// reload relationships for this model.
if (!policy && user) {
void entity.loadRelations();
}
}
}, [policies, policy, user, entity]);
return policies.abilities(entityId);
}