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

removable.ts

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