All files / src/hooks/queries useActivityLogQuery.ts

90.9% Statements 10/11
90% Branches 9/10
100% Functions 3/3
90% Lines 9/10

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                                            1x 12x     6x   6x 3x     3x     3x     3x     3x            
// src/hooks/queries/useActivityLogQuery.ts
import { useQuery } from '@tanstack/react-query';
import { fetchActivityLog } from '../../services/apiClient';
import { queryKeys } from '../../config/queryKeys';
import type { ActivityLogItem } from '../../types';
 
/**
 * Query hook for fetching the admin activity log.
 *
 * The activity log contains a record of all administrative actions
 * performed in the system. This data changes frequently as new
 * actions are logged, so it has a shorter stale time.
 *
 * @param limit - Maximum number of entries to fetch (default: 20)
 * @param offset - Number of entries to skip for pagination (default: 0)
 * @returns Query result with activity log entries
 *
 * @example
 * ```tsx
 * const { data: activityLog, isLoading, error } = useActivityLogQuery(20, 0);
 * ```
 */
export const useActivityLogQuery = (limit: number = 20, offset: number = 0) => {
  return useQuery({
    queryKey: queryKeys.activityLog(limit, offset),
    queryFn: async (): Promise<ActivityLogItem[]> => {
      const response = await fetchActivityLog(limit, offset);
 
      if (!response.ok) {
        const error = await response.json().catch(() => ({
          message: `Request failed with status ${response.status}`,
        }));
        throw new Error(error.message || 'Failed to fetch activity log');
      }
 
      const json = await response.json();
      // ADR-028: API returns { success: true, data: [...] }
      // If success is false or data is not an array, return empty array to prevent .map() errors
      Iif (!json.success || !Array.isArray(json.data)) {
        return [];
      }
      return json.data;
    },
    // Activity log changes frequently, keep stale time short
    staleTime: 1000 * 30, // 30 seconds
  });
};