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

queriesObserver.ts

216 lines5.8 KB

1import { notifyManager } from './notifyManager'
2import type {
3 QueryObserverOptions,
4 QueryObserverResult,
5 DefaultedQueryObserverOptions,
6} from './types'
7import type { QueryClient } from './queryClient'
8import type { NotifyOptions } from './queryObserver'
9import { QueryObserver } from './queryObserver'
10import { Subscribable } from './subscribable'
11​
12function difference<T>(array1: T[], array2: T[]): T[] {
13 return array1.filter((x) => array2.indexOf(x) === -1)
15​
16function replaceAt<T>(array: T[], index: number, value: T): T[] {
17 const copy = array.slice(0)
18 copy[index] = value
19 return copy
21​
22type QueriesObserverListener = (result: QueryObserverResult[]) => void
23​
24export class QueriesObserver extends Subscribable<QueriesObserverListener> {
25 #client: QueryClient
26 #result: QueryObserverResult[]
27 #queries: QueryObserverOptions[]
28 #observers: QueryObserver[]
29 #observersMap: Record<string, QueryObserver>
30​
31 constructor(client: QueryClient, queries?: QueryObserverOptions[]) {
32 super()
33​
34 this.#client = client
35 this.#queries = []
36 this.#result = []
37 this.#observers = []
38 this.#observersMap = {}
39​
40 if (queries) {
41 this.setQueries(queries)
42 }
43 }
44​
45 protected onSubscribe(): void {
46 if (this.listeners.length === 1) {
47 this.#observers.forEach((observer) => {
48 observer.subscribe((result) => {
49 this.#onUpdate(observer, result)
50 })
51 })
52 }
53 }
54​
55 protected onUnsubscribe(): void {
56 if (!this.listeners.length) {
57 this.destroy()
58 }
59 }
60​
61 destroy(): void {
62 this.listeners = []
63 this.#observers.forEach((observer) => {
64 observer.destroy()
65 })
66 }
67​
68 setQueries(
69 queries: QueryObserverOptions[],
70 notifyOptions?: NotifyOptions,
71 ): void {
72 this.#queries = queries
73​
74 notifyManager.batch(() => {
75 const prevObservers = this.#observers
76​
77 const newObserverMatches = this.#findMatchingObservers(this.#queries)
78​
79 // set options for the new observers to notify of changes
80 newObserverMatches.forEach((match) =>
81 match.observer.setOptions(match.defaultedQueryOptions, notifyOptions),
82 )
83​
84 const newObservers = newObserverMatches.map((match) => match.observer)
85 const newObserversMap = Object.fromEntries(
86 newObservers.map((observer) => [observer.options.queryHash, observer]),
87 )
88 const newResult = newObservers.map((observer) =>
89 observer.getCurrentResult(),
90 )
91​
92 const hasIndexChange = newObservers.some(
93 (observer, index) => observer !== prevObservers[index],
94 )
95 if (prevObservers.length === newObservers.length && !hasIndexChange) {
96 return
97 }
98​
99 this.#observers = newObservers
100 this.#observersMap = newObserversMap
101 this.#result = newResult
102​
103 if (!this.hasListeners()) {
104 return
105 }
106​
107 difference(prevObservers, newObservers).forEach((observer) => {
108 observer.destroy()
109 })
110​
111 difference(newObservers, prevObservers).forEach((observer) => {
112 observer.subscribe((result) => {
113 this.#onUpdate(observer, result)
114 })
115 })
116​
117 this.#notify()
118 })
119 }
120​
121 getCurrentResult(): QueryObserverResult[] {
122 return this.#result
123 }
124​
125 getQueries() {
126 return this.#observers.map((observer) => observer.getCurrentQuery())
127 }
128​
129 getObservers() {
130 return this.#observers
131 }
132​
133 getOptimisticResult(queries: QueryObserverOptions[]): QueryObserverResult[] {
134 return this.#findMatchingObservers(queries).map((match) =>
135 match.observer.getOptimisticResult(match.defaultedQueryOptions),
136 )
137 }
138​
139 #findMatchingObservers(
140 queries: QueryObserverOptions[],
141 ): QueryObserverMatch[] {
142 const prevObservers = this.#observers
143 const defaultedQueryOptions = queries.map((options) =>
144 this.#client.defaultQueryOptions(options),
145 )
146​
147 const matchingObservers: QueryObserverMatch[] =
148 defaultedQueryOptions.flatMap((defaultedOptions) => {
149 const match = prevObservers.find(
150 (observer) =>
151 observer.options.queryHash === defaultedOptions.queryHash,
152 )
153 if (match != null) {
154 return [{ defaultedQueryOptions: defaultedOptions, observer: match }]
155 }
156 return []
157 })
158​
159 const matchedQueryHashes = matchingObservers.map(
160 (match) => match.defaultedQueryOptions.queryHash,
161 )
162 const unmatchedQueries = defaultedQueryOptions.filter(
163 (defaultedOptions) =>
164 !matchedQueryHashes.includes(defaultedOptions.queryHash),
165 )
166​
167 const getObserver = (options: QueryObserverOptions): QueryObserver => {
168 const defaultedOptions = this.#client.defaultQueryOptions(options)
169 const currentObserver = this.#observersMap[defaultedOptions.queryHash!]
170 return (
171 currentObserver ?? new QueryObserver(this.#client, defaultedOptions)
172 )
173 }
174​
175 const newOrReusedObservers: QueryObserverMatch[] = unmatchedQueries.map(
176 (options) => {
177 return {
178 defaultedQueryOptions: options,
179 observer: getObserver(options),
180 }
181 },
182 )
183​
184 const sortMatchesByOrderOfQueries = (
185 a: QueryObserverMatch,
186 b: QueryObserverMatch,
187 ): number =>
188 defaultedQueryOptions.indexOf(a.defaultedQueryOptions) -
189 defaultedQueryOptions.indexOf(b.defaultedQueryOptions)
190​
191 return matchingObservers
192 .concat(newOrReusedObservers)
193 .sort(sortMatchesByOrderOfQueries)
194 }
195​
196 #onUpdate(observer: QueryObserver, result: QueryObserverResult): void {
197 const index = this.#observers.indexOf(observer)
198 if (index !== -1) {
199 this.#result = replaceAt(this.#result, index, result)
200 this.#notify()
201 }
202 }
203​
204 #notify(): void {
205 notifyManager.batch(() => {
206 this.listeners.forEach((listener) => {
207 listener(this.#result)
208 })
209 })
210 }
212​
213type QueryObserverMatch = {
214 defaultedQueryOptions: DefaultedQueryObserverOptions
215 observer: QueryObserver