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