All files / utils currentUser.js

100% Statements 20/20
100% Branches 5/5
100% Functions 6/6
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          486x 486x 83x 83x 71x 257x   1x   71x 71x   12x 12x               316x 316x 316x 1x 1x 1x   316x       1020x          
import { useMutation, useQuery, useQueryClient } from "react-query";
import axios from "axios";
import { useNavigate } from "react-router-dom"
 
export function useCurrentUser() {
  let rolesList = ["ERROR_GETTING_ROLES"];
  return useQuery("/api/currentUser", async () => {
    try {
      const response = await axios.get("/api/currentUser");
      try {
        rolesList = response.data.roles.map((r) => r.authority);
      } catch (e) {
        console.error("Error getting roles: ", e);
      }
      response.data = { ...response.data, rolesList: rolesList }
      return { loggedIn: true, root: response.data };
    } catch (e) {
      console.error("Error invoking axios.get: ", e);
      return { loggedIn: false, root: null };
    }
  }, {
    initialData: { loggedIn: false, root: null, initialData:true }
  });
}
 
export function useLogout() {
  const queryClient = useQueryClient();
  const navigate = useNavigate();
  const mutation = useMutation(async () => {
    await axios.post("/logout");
    await queryClient.resetQueries("/api/currentUser", { exact: true });
    navigate("/");
  })
  return mutation;
}
 
export function hasRole(currentUser, role) {
  return currentUser
    && currentUser.loggedIn
    && currentUser.root
    && currentUser.root.rolesList
    && currentUser.root.rolesList.includes(role)
}