useBucketPolicyCount.ts35 lines · main
| 1 | import { useCallback, useMemo } from 'react' |
| 2 | |
| 3 | import { extractBucketNameFromDefinition } from '@/components/interfaces/Storage/Storage.utils' |
| 4 | import { useDatabasePoliciesQuery } from '@/data/database-policies/database-policies-query' |
| 5 | import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject' |
| 6 | |
| 7 | export function useBucketPolicyCount() { |
| 8 | const { data: project, isPending: isProjectPending } = useSelectedProjectQuery() |
| 9 | const { data: policiesData = [], isPending: isPoliciesPending } = useDatabasePoliciesQuery({ |
| 10 | projectRef: project?.ref, |
| 11 | connectionString: project?.connectionString, |
| 12 | schema: 'storage', |
| 13 | }) |
| 14 | |
| 15 | const policyCountByBucket = useMemo(() => { |
| 16 | const countMap = new Map<string, number>() |
| 17 | for (const policy of policiesData) { |
| 18 | if (policy.table !== 'objects') continue |
| 19 | const bucketName = |
| 20 | extractBucketNameFromDefinition(policy.definition) ?? |
| 21 | extractBucketNameFromDefinition(policy.check) |
| 22 | if (bucketName) { |
| 23 | countMap.set(bucketName, (countMap.get(bucketName) ?? 0) + 1) |
| 24 | } |
| 25 | } |
| 26 | return countMap |
| 27 | }, [policiesData]) |
| 28 | |
| 29 | const getPolicyCount = useCallback( |
| 30 | (bucketName: string) => policyCountByBucket.get(bucketName) ?? 0, |
| 31 | [policyCountByBucket] |
| 32 | ) |
| 33 | |
| 34 | return { getPolicyCount, isLoading: isProjectPending || isPoliciesPending } |
| 35 | } |