All files / lib queryCacheEviction.ts

64.28% Statements 18/28
50% Branches 6/12
75% Functions 6/8
65.21% Lines 15/23

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  70x 70x   68x                   2x 2x     7x 68x   5x 5x       7x 7x 7x   7x 5x         7x    
/**
 * @see frontend/docs/UX/layer-contracts/L1-data-layer.md §3.4
 *
 * Tausta-ajo cache-entryjen aktiiviseen evikointiin. Poistaa observoimattomat
 * entryt joiden dataUpdatedAt on yli 2× gcTime (60 min) vanha. Ohittaa
 * eviktoinnin kokonaan offline-tilassa — koko tarkistussykli palautuu heti
 * kun navigator.onLine === false.
 *
 * Liittyy periaatteisiin: 8
 */

import type { QueryClient } from '@tanstack/react-query'
import { getOnlineDetector } from '@/lib/onlineDetector'
 
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 (!getOnlineDetector().isOnline()) 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)
}