93 lines
2.6 KiB
TypeScript
93 lines
2.6 KiB
TypeScript
/**
|
|
* React Query hooks for the ABAC Policy API.
|
|
*/
|
|
|
|
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
|
import {
|
|
fetchPolicies,
|
|
fetchPolicy,
|
|
createPolicy,
|
|
updatePolicy,
|
|
deletePolicy,
|
|
type CreatePolicyPayload,
|
|
type UpdatePolicyPayload,
|
|
} from './policies';
|
|
|
|
// ─── Query Key Factory ─────────────────────────────────────────────────────
|
|
|
|
export const policyKeys = {
|
|
all: ['policies'] as const,
|
|
list: (entityType: string) => [...policyKeys.all, 'list', entityType] as const,
|
|
detail: (entityType: string, policyId: string) =>
|
|
[...policyKeys.all, 'detail', entityType, policyId] as const,
|
|
};
|
|
|
|
// ─── Hooks ─────────────────────────────────────────────────────────────────
|
|
|
|
/**
|
|
* Fetch all policies for a given entity type.
|
|
*/
|
|
export function usePolicies(entityType: string) {
|
|
return useQuery({
|
|
queryKey: policyKeys.list(entityType),
|
|
queryFn: () => fetchPolicies(entityType),
|
|
enabled: !!entityType,
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Fetch a single policy by ID.
|
|
*/
|
|
export function usePolicy(entityType: string, policyId: string | null) {
|
|
return useQuery({
|
|
queryKey: policyKeys.detail(entityType, policyId!),
|
|
queryFn: () => fetchPolicy(entityType, policyId!),
|
|
enabled: !!entityType && !!policyId,
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Create a new policy.
|
|
*/
|
|
export function useCreatePolicy(entityType: string) {
|
|
const queryClient = useQueryClient();
|
|
return useMutation({
|
|
mutationFn: (payload: CreatePolicyPayload) => createPolicy(entityType, payload),
|
|
onSuccess: () => {
|
|
queryClient.invalidateQueries({ queryKey: policyKeys.list(entityType) });
|
|
},
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Update an existing policy.
|
|
*/
|
|
export function useUpdatePolicy(entityType: string) {
|
|
const queryClient = useQueryClient();
|
|
return useMutation({
|
|
mutationFn: ({
|
|
policyId,
|
|
data,
|
|
}: {
|
|
policyId: string;
|
|
data: UpdatePolicyPayload;
|
|
}) => updatePolicy(entityType, policyId, data),
|
|
onSuccess: () => {
|
|
queryClient.invalidateQueries({ queryKey: policyKeys.list(entityType) });
|
|
},
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Delete a policy.
|
|
*/
|
|
export function useDeletePolicy(entityType: string) {
|
|
const queryClient = useQueryClient();
|
|
return useMutation({
|
|
mutationFn: (policyId: string) => deletePolicy(entityType, policyId),
|
|
onSuccess: () => {
|
|
queryClient.invalidateQueries({ queryKey: policyKeys.list(entityType) });
|
|
},
|
|
});
|
|
}
|