All files / src/hooks/queries useFlyerItemsForFlyersQuery.ts

7.69% Statements 1/13
0% Branches 0/13
0% Functions 0/3
8.33% Lines 1/12

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                                          2x                                                              
// src/hooks/queries/useFlyerItemsForFlyersQuery.ts
import { useQuery } from '@tanstack/react-query';
import { fetchFlyerItemsForFlyers } from '../../services/apiClient';
import { queryKeys } from '../../config/queryKeys';
import type { FlyerItem } from '../../types';
 
/**
 * Query hook for fetching flyer items for multiple flyers.
 *
 * This is used to get all items from currently valid flyers,
 * which are then filtered against the user's watched items to find deals.
 *
 * @param flyerIds - Array of flyer IDs to fetch items for
 * @param enabled - Whether the query should run
 * @returns Query result with flyer items data
 *
 * @example
 * ```tsx
 * const { data: items } = useFlyerItemsForFlyersQuery(validFlyerIds, validFlyerIds.length > 0);
 * ```
 */
export const useFlyerItemsForFlyersQuery = (flyerIds: number[], enabled: boolean = true) => {
  return useQuery({
    // Include flyerIds in the key so cache is per-set of flyers
    queryKey: queryKeys.flyerItemsBatch(flyerIds),
    queryFn: async (): Promise<FlyerItem[]> => {
      if (flyerIds.length === 0) {
        return [];
      }
 
      const response = await fetchFlyerItemsForFlyers(flyerIds);
 
      if (!response.ok) {
        const error = await response.json().catch(() => ({
          message: `Request failed with status ${response.status}`,
        }));
        throw new Error(error.message || 'Failed to fetch flyer items');
      }
 
      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
      if (!json.success || !Array.isArray(json.data)) {
        return [];
      }
      return json.data;
    },
    enabled: enabled && flyerIds.length > 0,
    // Flyer items don't change frequently once created
    staleTime: 1000 * 60 * 5, // 5 minutes
  });
};