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

100% Statements 16/16
84.61% Branches 11/13
100% Functions 4/4
100% Lines 16/16

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                      72x 1153x 1153x   1153x 52x   1101x     1100x   7696x                 1100x   1100x     1100x         1x 1x       72x 1834x   244x    
import { useQuery } from "@tanstack/react-query";
import { Auth } from "aws-amplify";
import { CognitoUserAttributes } from "shared-types";
import { isCmsUser } from "shared-utils";
 
export type OneMacUser = {
  isCms?: boolean;
  user: CognitoUserAttributes | null;
  counties?: { label: string; value: string }[];
};
 
export const getUser = async (): Promise<OneMacUser> => {
  try {
    const currentAuthenticatedUser = await Auth.currentAuthenticatedUser();
 
    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,
      isCms: isCmsUser(userAttributesObj),
    } satisfies OneMacUser;
  } catch (e) {
    console.log({ e });
    return { user: null } satisfies OneMacUser;
  }
};
 
export const useGetUser = () =>
  useQuery({
    queryKey: ["user"],
    queryFn: () => getUser(),
  });