All files / lib queryCacheEviction.ts

100% Statements 14/14
100% Branches 6/6
100% Functions 4/4
100% Lines 12/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    2x 2x     7x 6x   5x 5x       7x 7x 7x   7x 5x         7x    
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)
}