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

88.23% Statements 15/17
86.66% Branches 13/15
100% Functions 4/4
88.23% Lines 15/17

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                          91x 1088x 1088x 1088x   1088x 14x   1074x     1074x   7514x                 1074x   1074x     1074x                   91x 2162x   216x    
import { useQuery } from "@tanstack/react-query";
import { Auth } from "aws-amplify";
import { CognitoUserAttributes, FullUser } from "shared-types";
import { isCmsUser } from "shared-utils";
 
import { getUserDetails } from "./useGetUserDetails";
 
export type OneMacUser = {
  isCms?: boolean;
  user: FullUser | null;
  counties?: { label: string; value: string }[];
};
 
export const getUser = async (): Promise<OneMacUser> => {
  try {
    const currentAuthenticatedUser = await Auth.currentAuthenticatedUser();
    const userDetails = await getUserDetails();
 
    if (!currentAuthenticatedUser) {
      return { user: null } satisfies OneMacUser;
    }
    const userAttributesArray = (await Auth.userAttributes(currentAuthenticatedUser)) || [];
 
    // Set object up with key/values from attributes array
    const userAttributesObj = userAttributesArray.reduce(
      (obj, item) =>
        item?.Name && item?.Value
          ? {
              ...obj,
              [item.Name]: item.Value,
            }
          : obj,
      {} as CognitoUserAttributes,
    );
    // Manual additions and normalizations
    userAttributesObj["custom:cms-roles"] = userAttributesObj["custom:cms-roles"] || "";
 
    userAttributesObj.username =
      currentAuthenticatedUser.username || currentAuthenticatedUser.Username || "";
 
    return {
      user: { ...userAttributesObj, role: userDetails.role, states: userDetails.states ?? [] },
      isCms: isCmsUser({ ...userAttributesObj, role: userDetails.role }),
    } satisfies OneMacUser;
  } catch (e) {
    console.log({ e });
    return { user: null } satisfies OneMacUser;
  }
};
 
export const useGetUser = () =>
  useQuery({
    queryKey: ["user"],
    queryFn: () => getUser(),
  });