All files / libs/tenants/teams/state/src/lib teams.queries.ts

100% Statements 74/74
100% Branches 27/27
90.9% Functions 10/11
100% Lines 58/58

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 591x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 142x 148x 148x 148x 188x 148x 148x 148x 148x 148x 148x 182x 188x 188x 188x 148x 148x 182x 728x 188x 148x 148x 182x 186x 30x 30x 188x 148x 182x 188x 98x 2603x 98x 98x 188x 188x 148x 148x 182x 188x 188x 188x 188x 188x 6x 1x 143x  
import { useIsFetching, useQuery } from '@tanstack/react-query';
import { keyBy } from 'lodash-es';
import { useEffect, useMemo } from 'react';
 
import { useSnackbars } from '@allshares/studio-design-system';
import { toError } from '@amalia/ext/typescript';
import { type TeamContract, type TeamMap } from '@amalia/tenants/teams/types';
 
import { TeamsApiClient } from './api-client/teams.api-client';
import { teamsQueryKeys } from './queries.keys';
 
export const useTeams = (
  { sortByName, showArchivedTeams = true }: { sortByName?: boolean; showArchivedTeams?: boolean } = {},
  options?: { enabled?: boolean },
) => {
  const { snackError } = useSnackbars();
 
  const {
    data: teams,
    isError,
    error,
    ...rest
  } = useQuery({
    queryKey: teamsQueryKeys.list(),
    queryFn: () => TeamsApiClient.getTeams(),
    ...options,
  });
 
  const filteredTeams = useMemo(
    () => (showArchivedTeams ? teams : teams?.filter((team) => !team.archived)),
    [showArchivedTeams, teams],
  );
 
  useEffect(() => {
    if (isError) {
      snackError(toError(error).message);
    }
  }, [isError, error, snackError]);
 
  const { teamsList, teamsMap }: { teamsList: TeamContract[]; teamsMap: TeamMap } = useMemo(
    () => ({
      teamsList: sortByName
        ? (filteredTeams ?? []).toSorted((a, b) => a.name.localeCompare(b.name))
        : (filteredTeams ?? []),
      teamsMap: keyBy(filteredTeams ?? [], 'id'),
    }),
    [filteredTeams, sortByName],
  );
 
  return {
    teamsList,
    teamsMap,
    isError,
    ...rest,
  };
};
 
export const useIsTeamsLoading = () => useIsFetching({ queryKey: teamsQueryKeys.all() }) > 0;