Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

removable.ts

49 lines1.5 KB

1import { timeoutManager } from './timeoutManager'
2import { isServer as isServerEnvironment } from './environmentManager'
3import { isValidTimeout } from './utils'
4import type { ManagedTimerId } from './timeoutManager'
5​
6/**
7 * The base class for cache entries that are garbage collected once nothing is using them β€”
8 * `Query` and `Mutation` both extend it. `gcTime` controls how long an unused entry is kept.
9 */
10export abstract class Removable {
11 gcTime!: number
12 #gcTimeout?: ManagedTimerId
13​
14 /**
15 * Clears the pending garbage collection timeout, so the entry is no longer scheduled for removal.
16 * A subclass may override this to release what it holds on to as well β€” `Query` also cancels any
17 * in-flight fetch.
18 */
19 destroy(): void {
20 this.clearGcTimeout()
21 }
22​
23 protected scheduleGc(): void {
24 this.clearGcTimeout()
25​
26 if (isValidTimeout(this.gcTime)) {
27 this.#gcTimeout = timeoutManager.setTimeout(() => {
28 this.optionalRemove()
29 }, this.gcTime)
30 }
31 }
32​
33 protected updateGcTime(newGcTime: number | undefined): void {
34 // Default to 5 minutes (Infinity for server-side) if no gcTime is set
35 this.gcTime = Math.max(
36 this.gcTime || 0,
37 newGcTime ?? (isServerEnvironment() ? Infinity : 5 * 60 * 1000),
38 )
39 }
40​
41 protected clearGcTimeout() {
42 if (this.#gcTimeout !== undefined) {
43 timeoutManager.clearTimeout(this.#gcTimeout)
44 this.#gcTimeout = undefined
45 }
46 }
47​
48 protected abstract optionalRemove(): void