All files / src/hooks/queries useAuthProfileQuery.ts

60% Statements 9/15
66.66% Branches 6/9
40% Functions 2/5
64.28% Lines 9/14

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 59 60 61 62 63 64 65                        39x                               39x 544x   544x     12x   10x             10x   9x                       39x              
// src/hooks/queries/useAuthProfileQuery.ts
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { getAuthenticatedUserProfile } from '../../services/apiClient';
import { getToken } from '../../services/tokenStorage';
import { queryKeys, queryKeyBases } from '../../config/queryKeys';
import type { UserProfile } from '../../types';
 
/**
 * Query key for the authenticated user's profile.
 * Exported for cache invalidation purposes.
 * @deprecated Use queryKeys.authProfile() from '../../config/queryKeys' instead
 */
export const AUTH_PROFILE_QUERY_KEY = queryKeys.authProfile();
 
/**
 * Query hook for fetching the authenticated user's profile.
 *
 * This query is used to validate the current auth token and retrieve
 * the user's profile data. It only runs when a token exists.
 *
 * @param enabled - Whether the query should run (default: true when token exists)
 * @returns TanStack Query result with UserProfile data
 *
 * @example
 * ```tsx
 * const { data: profile, isLoading, error } = useAuthProfileQuery();
 * ```
 */
export const useAuthProfileQuery = (enabled: boolean = true) => {
  const hasToken = !!getToken();
 
  return useQuery({
    queryKey: queryKeys.authProfile(),
    queryFn: async (): Promise<UserProfile> => {
      const response = await getAuthenticatedUserProfile();
 
      Iif (!response.ok) {
        const error = await response.json().catch(() => ({
          message: `Request failed with status ${response.status}`,
        }));
        throw new Error(error.message || 'Failed to fetch user profile');
      }
 
      const json = await response.json();
      // API returns { success: true, data: {...} }, extract the data object
      return json.data ?? json;
    },
    enabled: enabled && hasToken,
    staleTime: 1000 * 60 * 5, // 5 minutes
    retry: false, // Don't retry auth failures - they usually mean invalid token
  });
};
 
/**
 * Hook to manually invalidate the auth profile cache.
 * Useful after login or profile updates.
 */
export const useInvalidateAuthProfile = () => {
  const queryClient = useQueryClient();
 
  return () => {
    queryClient.invalidateQueries({ queryKey: queryKeyBases.authProfile });
  };
};