All files / src/common/utils queryKeyFactory.ts

45.12% Statements 111/246
84.78% Branches 39/46
24.61% Functions 16/65
45.12% Lines 111/246

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 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380                                  1x   1x 1x 1x 1x     1x 1x 1x 1x 30x     30x 30x 30x 30x 30x 30x 30x   30x 30x 1x 1x 145x     145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x 145x   145x 145x 1x 1x 1x 1x 1x 1x       1x 1x 1x 1x 1x 1x 1x 1x   1x   1x 1x 1x     1x 1x 1x 1x 1x 1x 1x 1x 1x     1x 1x 1x 1x       1x 1x 1x 1x 1x 1x 1x     1x 1x 1x 25x 25x 25x 1x 1x     1x   1x       1x       1x       1x       1x     1x       1x     1x 1x     1x   1x         1x         1x         1x                 1x         1x                       1x                   1x                   1x                         1x                         1x                                       1x               1x 1x             1x                                                                           1x                                       1x                                             1x                                  
import type { NewsletterFilter } from '../types/cache';
 
export interface QueryKeyFactoryParams {
  userId?: string;
  id?: string;
  filter?: NewsletterFilter;
  tagIds?: string[];
  sourceId?: string | null;
  groupSourceIds?: string[];
  timeRange?: string;
  position?: number;
}
 
/**
 * Centralized query key factory for consistent cache key generation
 * across all newsletter and reading queue operations
 */
export const queryKeyFactory: any = {
  // Root keys
  all: ['newsletters'] as const,
  readingQueue: ['readingQueue'] as const,
  tagRoot: ['tags'] as const,
  userRoot: ['user'] as const,
 
  // Newsletter keys
  newsletters: {
    all: () => [...queryKeyFactory.all] as const,
    lists: () => [...queryKeyFactory.newsletters.all(), 'list'] as const,
    list: (params: QueryKeyFactoryParams = {}) => {
      const baseKey = [...queryKeyFactory.newsletters.lists()] as const;
 
      // Build filters object excluding undefined values
      const filters: Record<string, unknown> = {};
      if (params.userId) filters.userId = params.userId;
      if (params.filter && typeof params.filter === 'object') filters.filter = params.filter;
      if (params.tagIds?.length) filters.tagIds = [...params.tagIds].sort(); // Sort for consistency
      if (params.sourceId !== undefined) filters.sourceId = params.sourceId;
      if (params.groupSourceIds?.length) filters.groupSourceIds = [...params.groupSourceIds].sort();
      if (params.timeRange && params.timeRange !== 'all') filters.timeRange = params.timeRange;
 
      return Object.keys(filters).length > 0 ? ([...baseKey, filters] as const) : baseKey;
    },
    infinites: () => [...queryKeyFactory.newsletters.all(), 'infinite'] as const,
    infinite: (filter: NewsletterFilter) => {
      const baseKey = [...queryKeyFactory.newsletters.infinites()] as const;
 
      // Build filters object for infinite query
      const filters: Record<string, unknown> = {};
      if (filter.search) filters.search = filter.search;
      if (filter.isRead !== undefined) filters.isRead = filter.isRead;
      if (filter.isArchived !== undefined) filters.isArchived = filter.isArchived;
      if (filter.isLiked !== undefined) filters.isLiked = filter.isLiked;
      if (filter.tagIds?.length) filters.tagIds = [...filter.tagIds].sort();
      if (filter.sourceIds?.length) filters.sourceIds = [...filter.sourceIds].sort();
      if (filter.groupIds?.length) filters.groupIds = [...filter.groupIds].sort();
      if (filter.dateFrom) filters.dateFrom = filter.dateFrom;
      if (filter.dateTo) filters.dateTo = filter.dateTo;
      if (filter.orderBy) filters.orderBy = filter.orderBy;
      if (filter.orderDirection) filters.orderDirection = filter.orderDirection;
 
      return Object.keys(filters).length > 0 ? ([...baseKey, filters] as const) : baseKey;
    },
    details: () => [...queryKeyFactory.newsletters.all(), 'detail'] as const,
    detail: (id: string) => [...queryKeyFactory.newsletters.details(), id] as const,
    tags: () => [...queryKeyFactory.newsletters.all(), 'tags'] as const,
    tag: (tagId: string) => [...queryKeyFactory.newsletters.tags(), tagId] as const,
    tagLists: () => [...queryKeyFactory.newsletters.tags(), 'list'] as const,
    tagList: (userId?: string) => {
      const baseKey = [...queryKeyFactory.newsletters.tagLists()] as const;
      return userId ? ([...baseKey, userId] as const) : baseKey;
    },
    tagDetails: () => [...queryKeyFactory.newsletters.tags(), 'detail'] as const,
    tagDetail: (tagId: string) => [...queryKeyFactory.newsletters.tagDetails(), tagId] as const,
    tagCounts: () => [...queryKeyFactory.newsletters.tags(), 'counts'] as const,
    sources: () => [...queryKeyFactory.newsletters.all(), 'sources'] as const,
    source: (sourceId: string) => [...queryKeyFactory.newsletters.sources(), sourceId] as const,
    sourceCounts: () => [...queryKeyFactory.newsletters.all(), 'source-counts'] as const,
    unreadCounts: () => [...queryKeyFactory.newsletters.all(), 'unread-counts'] as const,
    unreadCountsBySource: () =>
      [...queryKeyFactory.newsletters.unreadCounts(), 'by-source'] as const,
    totalCountsBySource: () =>
      [...queryKeyFactory.newsletters.all(), 'total-counts', 'by-source'] as const,
    byTags: () => [...queryKeyFactory.newsletters.all(), 'by-tags'] as const,
    inbox: () => [...queryKeyFactory.newsletters.all(), 'inbox'] as const,
  },
 
  // Reading queue keys
  queue: {
    all: () => [...queryKeyFactory.readingQueue] as const,
    lists: () => [...queryKeyFactory.queue.all(), 'list'] as const,
    list: (userId: string) => [...queryKeyFactory.queue.lists(), userId] as const,
    details: () => [...queryKeyFactory.queue.all(), 'detail'] as const,
    detail: (id: string) => [...queryKeyFactory.queue.details(), id] as const,
    positions: () => [...queryKeyFactory.queue.all(), 'positions'] as const,
    position: (userId: string) => [...queryKeyFactory.queue.positions(), userId] as const,
  },
 
  // Tag keys
  tags: {
    all: () => [...queryKeyFactory.tagRoot] as const,
    lists: () => [...queryKeyFactory.tags.all(), 'list'] as const,
    list: (userId?: string) => {
      const baseKey = [...queryKeyFactory.tags.lists()] as const;
      return userId ? ([...baseKey, userId] as const) : baseKey;
    },
    details: () => [...queryKeyFactory.tags.all(), 'detail'] as const,
    detail: (tagId: string) => [...queryKeyFactory.tags.details(), tagId] as const,
    counts: () => [...queryKeyFactory.tags.all(), 'counts'] as const,
    stats: () => [...queryKeyFactory.tags.all(), 'stats'] as const,
    usageStats: (tagId: string) => [...queryKeyFactory.tags.stats(), 'usage', tagId] as const,
    operations: (tagId: string) => [...queryKeyFactory.tags.detail(tagId), 'operations'] as const,
  },
 
  // User keys
  user: {
    all: () => [...queryKeyFactory.userRoot] as const,
    emailAlias: (userId?: string) => {
      const baseKey = [...queryKeyFactory.user.all(), 'email-alias'] as const;
      return userId ? ([...baseKey, userId] as const) : baseKey;
    },
    profile: (userId: string) => [...queryKeyFactory.user.all(), 'profile', userId] as const,
  },
 
  // Cross-feature keys for related data
  related: {
    // Keys for newsletter-queue relationships
    newsletterQueue: (newsletterId: string) =>
      [...queryKeyFactory.all, 'queue-status', newsletterId] as const,
 
    // Keys for tag-newsletter relationships
    tagNewsletters: (tagId: string) =>
      [...queryKeyFactory.newsletters.tags(), tagId, 'newsletters'] as const,
 
    // Keys for newsletter-tag relationships
    newsletterTags: (newsletterId: string) =>
      [...queryKeyFactory.newsletters.details(), newsletterId, 'tags'] as const,
 
    // Keys for tag operations
    tagOperations: (tagId: string) =>
      [...queryKeyFactory.newsletters.tags(), tagId, 'operations'] as const,
 
    // Keys for tag statistics and counts
    tagStats: () => [...queryKeyFactory.newsletters.tags(), 'stats'] as const,
 
    // Keys for source-newsletter relationships
    sourceNewsletters: (sourceId: string) =>
      [...queryKeyFactory.newsletters.sources(), sourceId, 'newsletters'] as const,
 
    // Keys for unread counts by source
    unreadCountsBySource: () => [...queryKeyFactory.newsletters.unreadCountsBySource()] as const,
 
    // Keys for newsletter counts by source
    newsletterCountsBySource: () => [...queryKeyFactory.newsletters.sourceCounts()] as const,
  },
 
  // Utility functions for query key matching
  matchers: {
    // Check if a query key matches newsletter list pattern
    isNewsletterListKey: (queryKey: unknown[]): boolean => {
      return queryKey.length >= 2 && queryKey[0] === 'newsletters' && queryKey[1] === 'list';
    },
 
    // Check if a query key matches newsletter infinite pattern
    isNewsletterInfiniteKey: (queryKey: unknown[]): boolean => {
      return queryKey.length >= 2 && queryKey[0] === 'newsletters' && queryKey[1] === 'infinite';
    },
 
    // Check if a query key matches reading queue pattern
    isReadingQueueKey: (queryKey: unknown[]): boolean => {
      return queryKey.length >= 1 && queryKey[0] === 'readingQueue';
    },
 
    // Check if a query key is for a specific newsletter
    isNewsletterDetailKey: (queryKey: unknown[], newsletterId?: string): boolean => {
      const isDetailKey =
        queryKey.length >= 3 && queryKey[0] === 'newsletters' && queryKey[1] === 'detail';
 
      if (!newsletterId) return isDetailKey;
      return isDetailKey && queryKey[2] === newsletterId;
    },
 
    // Check if a query key is tag-related
    isTagKey: (queryKey: unknown[]): boolean => {
      return queryKey.length >= 2 && queryKey[0] === 'newsletters' && queryKey[1] === 'tags';
    },
 
    // Check if a query key is for a specific tag
    isTagDetailKey: (queryKey: unknown[], tagId?: string): boolean => {
      const isTagKey =
        queryKey.length >= 4 &&
        queryKey[0] === 'newsletters' &&
        queryKey[1] === 'tags' &&
        queryKey[2] === 'detail';
 
      if (!tagId) return isTagKey;
      return isTagKey && queryKey[3] === tagId;
    },
 
    // Check if a query key is for tag lists
    isTagListKey: (queryKey: unknown[]): boolean => {
      return (
        queryKey.length >= 3 &&
        queryKey[0] === 'newsletters' &&
        queryKey[1] === 'tags' &&
        queryKey[2] === 'list'
      );
    },
 
    // Check if a query key involves a specific filter
    hasFilter: (queryKey: unknown[], filter: NewsletterFilter): boolean => {
      if (!queryKeyFactory.matchers.isNewsletterListKey(queryKey)) return false;
 
      const filtersObj = queryKey[2];
      if (typeof filtersObj !== 'object' || !filtersObj) return filter.status === 'all';
 
      return (filtersObj as Record<string, unknown>).filter === filter;
    },
 
    // Check if a query key involves specific tags
    hasTags: (queryKey: unknown[], tagIds: string[]): boolean => {
      if (!queryKeyFactory.matchers.isNewsletterListKey(queryKey)) return false;
 
      const filtersObj = queryKey[2];
      if (typeof filtersObj !== 'object' || !filtersObj) return tagIds.length === 0;
 
      const keyTagIds = (filtersObj as Record<string, unknown>).tagIds;
      if (!Array.isArray(keyTagIds)) return tagIds.length === 0;
 
      return keyTagIds.length === tagIds.length && keyTagIds.every((id) => tagIds.includes(id));
    },
 
    // Check if a query key involves any of the specified tags
    hasAnyTags: (queryKey: unknown[], tagIds: string[]): boolean => {
      if (!queryKeyFactory.matchers.isNewsletterListKey(queryKey)) return false;
 
      const filtersObj = queryKey[2];
      if (typeof filtersObj !== 'object' || !filtersObj) return false;
 
      const keyTagIds = (filtersObj as Record<string, unknown>).tagIds;
      if (!Array.isArray(keyTagIds)) return false;
 
      return keyTagIds.some((id) => tagIds.includes(id));
    },
 
    // Check if a query key is affected by tag changes
    isAffectedByTagChange: (queryKey: unknown[], tagId: string): boolean => {
      // Tag-related queries
      if (queryKeyFactory.matchers.isTagKey(queryKey)) {
        return queryKey.includes(tagId);
      }
 
      // Newsletter queries that might be filtered by tags
      if (queryKeyFactory.matchers.isNewsletterListKey(queryKey)) {
        return queryKeyFactory.matchers.hasAnyTags(queryKey, [tagId]);
      }
 
      // Newsletter detail queries might have tag relationships
      if (queryKeyFactory.matchers.isNewsletterDetailKey(queryKey)) {
        return true; // Tags might be part of the newsletter details
      }
 
      return false;
    },
 
    // Check if a query key involves a specific source
    hasSource: (queryKey: unknown[], sourceId: string | null): boolean => {
      if (!queryKeyFactory.matchers.isNewsletterListKey(queryKey)) return false;
 
      const filtersObj = queryKey[2];
      if (typeof filtersObj !== 'object' || !filtersObj) return sourceId === null;
 
      return (filtersObj as Record<string, unknown>).sourceId === sourceId;
    },
  },
};
 
/**
 * Legacy compatibility function - maintains backward compatibility
 * with existing usage while encouraging migration to new factory
 * @deprecated Use queryKeyFactory methods instead
 */
export const buildQueryKey = (params: {
  scope: 'list' | 'detail' | 'tags';
  userId?: string;
  id?: string;
  filter?: NewsletterFilter;
  tagId?: string;
  sourceId?: string | null;
  groupSourceIds?: string[];
  timeRange?: string;
}) => {
  const { scope, userId, id, filter, tagId, sourceId, groupSourceIds, timeRange } = params;
 
  if (scope === 'list') {
    return queryKeyFactory.newsletters.list({
      userId,
      filter,
      tagIds: tagId ? [tagId] : undefined,
      sourceId,
      groupSourceIds,
      timeRange,
    });
  }
 
  if (scope === 'detail' && id) {
    return queryKeyFactory.newsletters.detail(id);
  }
 
  if (scope === 'tags') {
    return tagId ? queryKeyFactory.newsletters.tag(tagId) : queryKeyFactory.newsletters.tags();
  }
 
  // Fallback to basic key
  return [scope];
};
 
/**
 * Type-safe query key generator with validation
 */
export const createQueryKey = (category: string, ...args: unknown[]): readonly unknown[] => {
  const factory = (queryKeyFactory as any)[category];
 
  if (typeof factory === 'function') {
    return (factory as (...args: unknown[]) => readonly unknown[])(...args);
  }
 
  if (typeof factory === 'object' && args.length > 0) {
    const method = (factory as Record<string, unknown>)[args[0] as string];
    if (typeof method === 'function') {
      return (method as (...args: unknown[]) => readonly unknown[])(...args.slice(1));
    }
  }
 
  throw new Error(`Invalid query key configuration: ${String(category)}`);
};
 
/**
 * Utility to normalize query keys for comparison and caching
 */
export const normalizeQueryKey = (queryKey: unknown[]): string => {
  return JSON.stringify(queryKey, (_, value) => {
    // Sort arrays for consistent string representation
    if (Array.isArray(value)) {
      return [...value].sort();
    }
    // Sort object keys for consistent string representation
    if (typeof value === 'object' && value !== null) {
      const sorted: Record<string, unknown> = {};
      Object.keys(value)
        .sort()
        .forEach((k) => {
          sorted[k] = (value as Record<string, unknown>)[k];
        });
      return sorted;
    }
    return value;
  });
};
 
/**
 * Debug utility to help identify query key patterns
 */
export const debugQueryKey = (queryKey: unknown[]): string => {
  const patterns = [];
 
  if (queryKeyFactory.matchers.isNewsletterListKey(queryKey)) {
    patterns.push('newsletter-list');
  }
 
  if (queryKeyFactory.matchers.isReadingQueueKey(queryKey)) {
    patterns.push('reading-queue');
  }
 
  if (queryKeyFactory.matchers.isNewsletterDetailKey(queryKey)) {
    patterns.push('newsletter-detail');
  }
 
  return `QueryKey: ${JSON.stringify(queryKey)} | Patterns: [${patterns.join(', ')}]`;
};