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 27 28 29 30 31 32 33 34 35 36 37 38 39  69x 69x   66x                             66x                                      
/**
 * @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)
}