All files / lib queryCacheEviction.ts

28.57% Statements 4/14
0% Branches 0/6
25% Functions 1/4
33.33% Lines 4/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 2737x 37x   37x                             37x                
import type { QueryClient } from '@tanstack/react-query'
 
const RETENTION_THRESHOLD_MS = 2 * 30 * 60 * 1000
const EVICTION_INTERVAL_MS = 5 * 60 * 1000

export function startCacheEviction(queryClient: QueryClient): () => void {
  const interval = setInterval(() => {
    if (!navigator.onLine) return

    const now = Date.now()
    queryClient
      .getQueryCache()
      .getAll()
      .forEach((query) => {
        const isInactive = query.getObserversCount() === 0
        const lastUpdated = query.state.dataUpdatedAt
        const age = now - lastUpdated
 
        if (isInactive && age > RETENTION_THRESHOLD_MS) {
          queryClient.removeQueries({ queryKey: query.queryKey, exact: true })
        }
      })
  }, EVICTION_INTERVAL_MS)
 
  return () => clearInterval(interval)
}