All files / react-app/src/api useGetTypes.ts

66.66% Statements 12/18
78.57% Branches 11/14
42.85% Functions 3/7
66.66% Lines 10/15

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                      8x 8x   8x 8x 6x   6x 4x   3x     2x 2x                                                            
import { API } from "aws-amplify";
import { useQuery, UseQueryOptions } from "@tanstack/react-query";
import { opensearch, ReactQueryApiError } from "shared-types";
import { subtypes, types } from "shared-types/opensearch";
 
type FetchOptions = {
  authorityId: number | string;
  typeIds?: number[] | string[];
};
 
export async function fetchData<T>({ authorityId, typeIds }: FetchOptions): Promise<T[]> {
  const endpoint = typeIds ? "/getSubTypes" : "/getTypes";
  const body = typeIds ? { authorityId, typeIds } : { authorityId };
 
  try {
    const response = await API.post("os", endpoint, { body });
    const hits = response.hits?.hits || [];
 
    if (typeIds) {
      return hits.map((hit: subtypes.ItemResult) => hit._source as T);
    } else {
      return hits.map((hit: types.ItemResult) => hit._source as T);
    }
  } catch (error) {
    console.error(`Error fetching ${typeIds ? "subtypes" : "types"}:`, error);
    throw new Error(`Failed to fetch ${typeIds ? "subtypes" : "types"}`);
  }
}
 
export function useGetData<T>(
  options: FetchOptions,
  queryOptions?: UseQueryOptions<T[], ReactQueryApiError>,
) {
  const { authorityId, typeIds } = options;
  const queryKey = typeIds
    ? ["package-subtypes", authorityId, typeIds]
    : ["package-types", authorityId];
 
  return useQuery<T[], ReactQueryApiError>(queryKey, () => fetchData<T>(options), queryOptions);
}
 
export function useGetTypes(
  authorityId: number | string,
  options?: UseQueryOptions<opensearch.types.Document[], ReactQueryApiError>,
) {
  return useGetData<opensearch.types.Document>({ authorityId }, options);
}
 
export function useGetSubTypes(
  authorityId: number | string,
  typeIds: number[] | string[],
  options?: UseQueryOptions<opensearch.subtypes.Document[], ReactQueryApiError>,
) {
  return useGetData<opensearch.subtypes.Document>({ authorityId, typeIds }, options);
}