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 getOptimisticResult(queries: QueryObserverOptions[]): QueryObserverResult[] {
121 return this.findMatchingObservers(queries).map((match) =>
122 match.observer.getOptimisticResult(match.defaultedQueryOptions),
123 )
124 }
125β
126 private findMatchingObservers(
127 queries: QueryObserverOptions[],
128 ): QueryObserverMatch[] {
129 const prevObservers = this.observers
130 const defaultedQueryOptions = queries.map((options) =>
131 this.client.defaultQueryOptions(options),
132 )
133β
134 const matchingObservers: QueryObserverMatch[] =
135 defaultedQueryOptions.flatMap((defaultedOptions) => {
136 const match = prevObservers.find(
137 (observer) =>
138 observer.options.queryHash === defaultedOptions.queryHash,
139 )
140 if (match != null) {
141 return [{ defaultedQueryOptions: defaultedOptions, observer: match }]
142 }
143 return []
144 })
145β
146 const matchedQueryHashes = matchingObservers.map(
147 (match) => match.defaultedQueryOptions.queryHash,
148 )
149 const unmatchedQueries = defaultedQueryOptions.filter(
150 (defaultedOptions) =>
151 !matchedQueryHashes.includes(defaultedOptions.queryHash),
152 )
153β
154 const unmatchedObservers = prevObservers.filter(
155 (prevObserver) =>
156 !matchingObservers.some((match) => match.observer === prevObserver),
157 )
158β
159 const getObserver = (options: QueryObserverOptions): QueryObserver => {
160 const defaultedOptions = this.client.defaultQueryOptions(options)
161 const currentObserver = this.observersMap[defaultedOptions.queryHash!]
162 return currentObserver ?? new QueryObserver(this.client, defaultedOptions)
163 }
164β
165 const newOrReusedObservers: QueryObserverMatch[] = unmatchedQueries.map(
166 (options, index) => {
167 if (options.keepPreviousData) {
168 // return previous data from one of the observers that no longer match
169 const previouslyUsedObserver = unmatchedObservers[index]
170 if (previouslyUsedObserver !== undefined) {
171 return {
172 defaultedQueryOptions: options,
173 observer: previouslyUsedObserver,
174 }
175 }
176 }
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 private 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 private notify(): void {
205 notifyManager.batch(() => {
206 this.listeners.forEach((listener) => {
207 listener(this.result)
208 })
209 })
210 }
211}
212β
213type QueryObserverMatch = {
214 defaultedQueryOptions: DefaultedQueryObserverOptions
215 observer: QueryObserver
216}