All files / src/common/hooks useNewsletterSources.ts

65.27% Statements 94/144
50% Branches 4/8
15.38% Functions 2/13
65.27% Lines 94/144

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 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 2101x 1x     1x 1x 1x     1x 1x     1x 1x 1x 1x 1x 24x 24x 24x 24x 24x 1x                                   1x 24x 24x 24x     24x 24x 24x 24x 24x 24x 24x 24x 24x   24x 24x 24x 24x     24x 12x 24x     24x 24x         24x 24x     24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x       24x 24x 24x 24x 24x 24x     24x     24x   24x     24x         24x 24x             24x                 24x           24x     24x     24x         24x 24x             24x                               24x           24x     24x     24x 24x     24x 24x   24x   24x 24x 24x 24x 24x 24x 24x     24x 24x 24x     24x 24x 24x  
import { AuthContext } from '@common/contexts/AuthContext';
import { newsletterSourceService } from '@common/services';
import { NewsletterSource } from '@common/types';
import { NewsletterSourceQueryParams, PaginatedResponse } from '@common/types/api';
import { getCacheManagerSafe } from '@common/utils/cacheUtils';
import { keepPreviousData, useMutation, useQuery } from '@tanstack/react-query';
import { useCallback, useContext, useMemo } from 'react';
 
// Cache time constants (in milliseconds)
const STALE_TIME = 5 * 60 * 1000; // 5 minutes
const CACHE_TIME = 30 * 60 * 1000; // 30 minutes
 
// Query keys
const queryKeys = {
  all: ['newsletterSources'],
  lists: () => [...queryKeys.all, 'list'],
  detail: (id: string) => [...queryKeys.all, 'detail', id],
  userSources: (userId: string, params?: NewsletterSourceQueryParams) => [
    ...queryKeys.all,
    'user',
    userId,
    ...(params ? [params] : []),
  ],
};
 
// Types
interface UpdateNewsletterSourceVars {
  id: string;
  name: string;
}
 
interface ArchiveNewsletterSourceVars {
  id: string;
  archive: boolean;
}
 
type SourceContext = {
  previousSources?: NewsletterSource[];
};
 
// Hook
export const useNewsletterSources = (params: NewsletterSourceQueryParams = {}) => {
  const auth = useContext(AuthContext);
  const user = auth?.user;
  const userId = user?.id || '';
 
  // Default parameters for getting active sources with counts
  const queryParams = useMemo(
    () => {
      const merged: NewsletterSourceQueryParams = {
        excludeArchived: true,
        includeCount: true,
        orderBy: 'created_at',
        orderDirection: 'desc',
        ...params,
      };
 
      return merged;
    },
    [params]
  );
 
  // Initialize cache manager safely
  const cacheManager = useMemo(() => {
    return getCacheManagerSafe();
  }, []);
 
  // Safe cache manager helper
  const safeCacheCall = useCallback(
    (fn: (manager: NonNullable<ReturnType<typeof getCacheManagerSafe>>) => void) => {
      if (cacheManager) {
        fn(cacheManager);
      }
    },
    [cacheManager]
  );
 
  // Query for newsletter sources using the API layer
  const {
    data: sourcesResponse,
    isLoading: isLoadingSources,
    isError: isErrorSources,
    error: errorSources,
    isFetching: isFetchingSources,
    isStale: isStaleSources,
    refetch: refetchSources,
  } = useQuery<PaginatedResponse<NewsletterSource>, Error>({
    queryKey: queryKeys.userSources(userId, queryParams),
    queryFn: async () => {
      const result = await newsletterSourceService.getSources(queryParams);
      return result;
    },
    enabled: !!user,
    staleTime: STALE_TIME,
    gcTime: CACHE_TIME,
    placeholderData: keepPreviousData,
    refetchOnWindowFocus: false,
  });
 
  // Extract newsletter sources from paginated response
  const newsletterSources = sourcesResponse?.data || [];
 
  // Invalidate and refetch
  const invalidateSources = useCallback(async () => {
    safeCacheCall((manager) => manager.invalidateRelatedQueries([], 'newsletter-sources'));
  }, [safeCacheCall]);
 
  // Update mutation using API layer
  const updateMutation = useMutation<
    NewsletterSource,
    Error,
    UpdateNewsletterSourceVars,
    SourceContext
  >({
    mutationFn: async ({ id, name }) => {
      const result = await newsletterSourceService.updateSource(id, { id, name });
      if (!result.success) {
        throw new Error(result.error || 'Failed to update source');
      }
      return result.source!; // Use non-null assertion since we check success above
    },
    onMutate: async () => {
      // Use cache manager for optimistic update
      const previousSources = newsletterSources;
 
      // Apply optimistic update with the new name
      safeCacheCall((manager) => manager.invalidateRelatedQueries([], 'source-update-optimistic'));
 
      return { previousSources };
    },
    onError: (_, __, context) => {
      // Revert optimistic update using cache manager
      if (context?.previousSources) {
        safeCacheCall((manager) => manager.invalidateRelatedQueries([], 'source-update-error'));
      }
    },
    onSettled: () => {
      invalidateSources();
    },
  });
 
  // Archive mutation using API layer
  const archiveMutation = useMutation<
    NewsletterSource,
    Error,
    ArchiveNewsletterSourceVars,
    SourceContext
  >({
    mutationFn: async ({ id }) => {
      const result = await newsletterSourceService.toggleArchive(id);
      if (!result.success || !result.source) {
        throw new Error(result.error || 'Failed to toggle archive status');
      }
      return result.source;
    },
    onMutate: async ({ archive }) => {
      const previousSources = newsletterSources;
 
      // Use cache manager for optimistic update
      if (archive) {
        safeCacheCall((manager) =>
          manager.invalidateRelatedQueries([], 'source-archive-optimistic')
        );
      } else {
        safeCacheCall((manager) =>
          manager.invalidateRelatedQueries([], 'source-unarchive-optimistic')
        );
      }
 
      return { previousSources };
    },
    onError: (_, __, context) => {
      // Revert optimistic update using cache manager
      if (context?.previousSources) {
        safeCacheCall((manager) => manager.invalidateRelatedQueries([], 'source-archive-error'));
      }
    },
    onSettled: () => {
      invalidateSources();
    },
  });
 
  // Archive or unarchive a source
  const setSourceArchiveStatus = useCallback(
    async (sourceId: string, archive: boolean) => {
      return archiveMutation.mutateAsync({ id: sourceId, archive });
    },
    [archiveMutation]
  );
 
  return {
    // Source data
    newsletterSources,
    isLoadingSources,
    isErrorSources,
    errorSources,
    isFetchingSources,
    isStaleSources,
    refetchSources,
 
    // Source actions
    updateSource: updateMutation.mutateAsync,
    setSourceArchiveStatus,
    isArchivingSource: archiveMutation.isPending,
 
    // Raw query data
    sourcesResponse,
  };
};