Files
outline/app/hooks/usePolicy.ts
Tom Moor 79764b1e64 chore: Improve relationship loading, include policies (#6321)
Use model where available in usePolicy
2023-12-28 08:51:33 -08:00

31 lines
860 B
TypeScript

import * as React from "react";
import Model from "~/models/base/Model";
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 entityId = entity
? typeof entity === "string"
? entity
: entity.id
: "";
React.useEffect(() => {
if (entity && typeof entity !== "string") {
// The policy for this model is missing, reload relationships for this model.
if (!policies.get(entity.id)) {
void entity.loadRelations();
}
}
}, [policies, entity]);
return policies.abilities(entityId);
}