All files / src/hooks usePiiKinds.ts

100% Statements 24/24
100% Branches 2/2
100% Functions 10/10
100% Lines 19/19

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59                                142x 142x   27x     142x 142x   142x   134x               142x   134x 134x 116x 116x 61x 61x   116x   134x     142x 134x       142x        
import { PiiKindSpec, piiKinds, RuleCatalogue } from "@/objects/Rule";
import { QUERY_KEYS } from "@/services/query_keys";
import { useApiHandler } from "@/services/useApiHandler";
import { useQuery } from "@tanstack/react-query";
import { useMemo } from "react";
 
/**
 * The kinds of personal data svc-core's PII detectors know, from the rule
 * catalogue.
 *
 * The rule builder's pickers and every place a redaction is described
 * ("2 NHS numbers") read the detectors' own registry through this, rather
 * than a list kept in the frontend that a new detector would leave behind.
 * Shares the builder's catalogue query, which never changes in a session.
 */
export function usePiiKinds() {
  const { getApiHandler } = useApiHandler();
  const { data } = useQuery<RuleCatalogue | null>({
    queryKey: [QUERY_KEYS.GET.RULE_CATALOGUE],
    queryFn: () => getApiHandler().rule_router.catalogue(),
    staleTime: Infinity,
  });
  const catalogue = data as RuleCatalogue | null | undefined;
  const kinds = useMemo(() => piiKinds(catalogue), [catalogue]);
 
  const byKey = useMemo(
    () =>
      Object.fromEntries(kinds.map((kind) => [kind.key, kind])) as Record<
        string,
        PiiKindSpec
      >,
    [kinds],
  );
 
  /** Kinds under their region's heading, in the registry's order. */
  const byRegion = useMemo(() => {
    const groups: { region: string; label: string; kinds: PiiKindSpec[] }[] =
      [];
    for (const kind of kinds) {
      let group = groups.find((g) => g.region === kind.region);
      if (!group) {
        group = { region: kind.region, label: kind.region_label, kinds: [] };
        groups.push(group);
      }
      group.kinds.push(kind);
    }
    return groups;
  }, [kinds]);
 
  const defaults = useMemo(
    () => kinds.filter((kind) => kind.default).map((kind) => kind.key),
    [kinds],
  );
 
  return { kinds, byKey, byRegion, defaults };
}
 
export default usePiiKinds;