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

removable.ts

65 lines2.1 KB

1import { isServer as isServerEnvironment } from './environmentManager'
2import { timeoutManager } from './timeoutManager'
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 /**
24 * Schedules the entry to be removed from its cache after `gcTime`, replacing any timeout scheduled
25 * before. Nothing is scheduled if `gcTime` is `Infinity`.
26 */
27 protected scheduleGc(): void {
28 this.clearGcTimeout()
29​
30 if (isValidTimeout(this.gcTime)) {
31 this.#gcTimeout = timeoutManager.setTimeout(() => {
32 this.optionalRemove()
33 }, this.gcTime)
34 }
35 }
36​
37 /**
38 * Updates `gcTime`, keeping the longest one seen so far. Without a value, it defaults to 5 minutes
39 * on the client and `Infinity` on the server.
40 * @param newGcTime - The `gcTime` from the latest options, if any.
41 */
42 protected updateGcTime(newGcTime: number | undefined): void {
43 // Default to 5 minutes (Infinity for server-side) if no gcTime is set
44 this.gcTime = Math.max(
45 this.gcTime || 0,
46 newGcTime ?? (isServerEnvironment() ? Infinity : 5 * 60 * 1000),
47 )
48 }
49​
50 /**
51 * Cancels the scheduled removal, if there is one.
52 */
53 protected clearGcTimeout() {
54 if (this.#gcTimeout !== undefined) {
55 timeoutManager.clearTimeout(this.#gcTimeout)
56 this.#gcTimeout = undefined
57 }
58 }
59​
60 /**
61 * Called when the garbage collection timeout fires. Subclasses remove the entry from its cache
62 * unless it is still in use, e.g. because it has observers.
63 */
64 protected abstract optionalRemove(): void