All files / src/common/hooks useCache.ts

100% Statements 176/176
76.31% Branches 29/38
100% Functions 1/1
100% Lines 176/176

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 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 2441x 1x                         1x   278x 121x 121x 121x     29x 29x 278x     278x 278x 2x 1x 1x 1x 1x 2x 278x 278x   278x 278x 1x 1x 1x 1x 1x 278x 278x   278x 278x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 278x 278x     278x 278x               1x 1x 1x 1x 278x 278x     278x 278x 1x 1x 1x 278x 278x   278x 1x 1x 278x   278x 1x 1x 278x     278x 278x 2x 2x 2x 278x 278x     278x 278x 2x   2x 2x 2x 2x 2x 2x   2x 1x 1x   1x 1x 2x 278x 278x     278x 278x 2x 2x 2x 2x 2x 2x 2x 2x 2x   2x 1x 1x   1x 1x 2x 278x 278x     278x 278x 2x 2x 2x 2x 2x 2x 2x 2x 2x 278x 278x   278x 278x 1x 1x 1x 1x 1x 278x 278x   278x 278x 1x 1x 278x 278x   278x   1x 278x     278x 278x 3x       3x 3x 3x 1x 3x 1x 1x 1x 3x   3x 3x 278x 278x   278x   278x 278x 278x     278x     278x 278x 278x 278x 278x     278x     278x 278x 278x 278x 278x     278x 278x 278x  
import { useMemo, useCallback } from "react";
import {
  getCacheManager,
  prefetchQuery as utilsPrefetchQuery,
  setQueryData as utilsSetQueryData,
  getQueryData as utilsGetQueryData,
  invalidateQueries,
} from "@common/utils/cacheUtils";
import type { NewsletterWithRelations, ReadingQueueItem } from "@common/types";
 
/**
 * Custom hook that provides a unified interface for cache operations
 * Uses the SimpleCacheManager internally to ensure consistent cache management
 */
export const useCache = () => {
  // Initialize or get existing cache manager instance
  const cacheManager = useMemo(() => {
    try {
      return getCacheManager();
    } catch {
      // If no cache manager exists, this means it needs to be initialized elsewhere
      // Return null and handle gracefully
      return null;
    }
  }, []);
 
  // Newsletter cache operations
  const updateNewsletter = useCallback(
    (newsletterId: string, updates: Partial<NewsletterWithRelations>) => {
      if (!cacheManager) return;
      cacheManager.updateNewsletterInCache({
        id: newsletterId,
        updates,
      });
    },
    [cacheManager],
  );
 
  const batchUpdateNewsletters = useCallback(
    async (
      updates: { id: string; updates: Partial<NewsletterWithRelations> }[],
    ) => {
      if (!cacheManager) return;
      await cacheManager.batchUpdateNewsletters(updates);
    },
    [cacheManager],
  );
 
  const optimisticUpdate = useCallback(
    async (
      newsletterId: string,
      updates: Partial<NewsletterWithRelations>,
      operation: string,
    ): Promise<NewsletterWithRelations | null> => {
      if (!cacheManager) return null;
      return await cacheManager.optimisticUpdate(
        newsletterId,
        updates,
        operation,
      );
    },
    [cacheManager],
  );
 
  // Reading queue cache operations
  const updateReadingQueue = useCallback(
    (operation: {
      type: "add" | "remove" | "reorder" | "updateTags" | "revert";
      newsletterId?: string;
      queueItemId?: string;
      updates?: { id: string; position: number }[];
      tagIds?: string[];
      queueItems?: ReadingQueueItem[];
      userId: string;
    }) => {
      if (!cacheManager) return;
      cacheManager.updateReadingQueueInCache(operation);
    },
    [cacheManager],
  );
 
  // Query invalidation operations
  const invalidateRelatedQueries = useCallback(
    (newsletterIds: string[], operationType: string) => {
      if (!cacheManager) return;
      cacheManager.invalidateRelatedQueries(newsletterIds, operationType);
    },
    [cacheManager],
  );
 
  const invalidateNewsletters = useCallback(() => {
    if (!cacheManager) return;
    cacheManager.clearNewsletterCache();
  }, [cacheManager]);
 
  const invalidateReadingQueue = useCallback(() => {
    if (!cacheManager) return;
    cacheManager.clearReadingQueueCache();
  }, [cacheManager]);
 
  // Cache warming operations
  const warmCache = useCallback(
    (userId: string, priority: "high" | "medium" | "low" = "medium") => {
      if (!cacheManager) return;
      cacheManager.warmCache(userId, priority);
    },
    [cacheManager],
  );
 
  // Tag-specific cache operations (extending cache manager functionality)
  const invalidateTagQueries = useCallback(
    (tagIds: string[], operationType: string) => {
      if (!cacheManager) return;
      // Use the generic invalidateRelatedQueries with tag-specific operation types
      const tagOperationTypes = [
        "tag-create",
        "tag-update",
        "tag-delete",
        "newsletter-tag-update",
      ];
 
      if (tagOperationTypes.includes(operationType)) {
        cacheManager.invalidateRelatedQueries(tagIds, operationType);
      } else {
        // Fallback for tag operations
        cacheManager.invalidateRelatedQueries([], "tag-update");
      }
    },
    [cacheManager],
  );
 
  // Newsletter source cache operations
  const invalidateSourceQueries = useCallback(
    (sourceIds: string[], operationType: string) => {
      if (!cacheManager) return;
      const sourceOperationTypes = [
        "newsletter-sources",
        "source-update-optimistic",
        "source-update-error",
        "source-archive-optimistic",
        "source-unarchive-optimistic",
        "source-archive-error",
      ];
 
      if (sourceOperationTypes.includes(operationType)) {
        cacheManager.invalidateRelatedQueries(sourceIds, operationType);
      } else {
        // Fallback for source operations
        cacheManager.invalidateRelatedQueries([], "newsletter-sources");
      }
    },
    [cacheManager],
  );
 
  // Generic cache utilities
  const prefetchQuery = useCallback(
    (
      queryKey: readonly unknown[],
      queryFn: () => Promise<unknown>,
      options?: { staleTime?: number; gcTime?: number },
    ) => {
      return utilsPrefetchQuery(queryKey, queryFn, {
        staleTime: options?.staleTime || 5 * 60 * 1000,
        gcTime: options?.gcTime || 30 * 60 * 1000,
      });
    },
    [],
  );
 
  const setQueryData = useCallback(
    <T>(
      queryKey: readonly unknown[],
      data: T | ((oldData: T | undefined) => T),
    ) => {
      return utilsSetQueryData(queryKey, data);
    },
    [],
  );
 
  const getQueryData = useCallback(
    <T>(queryKey: readonly unknown[]): T | undefined => {
      return utilsGetQueryData<T>(queryKey);
    },
    [],
  );
 
  const removeQueries = useCallback(async (queryKey: readonly unknown[]) => {
    // Use invalidateQueries with exact matching for removal
    await invalidateQueries({ queryKey });
  }, []);
 
  // Batch operations for performance
  const batchInvalidate = useCallback(
    async (
      operations: Array<{
        queryKey?: readonly unknown[];
        predicate?: (query: unknown) => boolean;
      }>,
    ) => {
      const promises = operations.map((op) => {
        if (op.queryKey) {
          return invalidateQueries({ queryKey: op.queryKey });
        } else if (op.predicate) {
          return invalidateQueries({ predicate: op.predicate });
        }
        return Promise.resolve();
      });
 
      await Promise.all(promises);
    },
    [],
  );
 
  return {
    // Newsletter operations
    updateNewsletter,
    batchUpdateNewsletters,
    optimisticUpdate,
 
    // Reading queue operations
    updateReadingQueue,
 
    // Invalidation operations
    invalidateRelatedQueries,
    invalidateNewsletters,
    invalidateReadingQueue,
    invalidateTagQueries,
    invalidateSourceQueries,
 
    // Cache warming
    warmCache,
 
    // Generic utilities
    prefetchQuery,
    setQueryData,
    getQueryData,
    removeQueries,
    batchInvalidate,
 
    // Direct access to cache manager for advanced use cases
    cacheManager,
  };
};