Open History to see the last commit
1import type { Mutation } from './mutation'
2import type { Query } from './query'
3import type {
4 FetchStatus,
5 MutationKey,
6 MutationStatus,
7 QueryKey,
8 QueryOptions,
9} from './types'
10β
11// TYPES
12β
13export interface QueryFilters {
14 /**
15 * Filter to active queries, inactive queries or all queries
16 */
17 type?: QueryTypeFilter
18 /**
19 * Match query key exactly
20 */
21 exact?: boolean
22 /**
23 * Include queries matching this predicate function
24 */
25 predicate?: (query: Query) => boolean
26 /**
27 * Include queries matching this query key
28 */
29 queryKey?: QueryKey
30 /**
31 * Include or exclude stale queries
32 */
33 stale?: boolean
34 /**
35 * Include queries matching their fetchStatus
36 */
37 fetchStatus?: FetchStatus
38}
39β
40export interface MutationFilters {
41 /**
42 * Match mutation key exactly
43 */
44 exact?: boolean
45 /**
46 * Include mutations matching this predicate function
47 */
48 predicate?: (mutation: Mutation<any, any, any>) => boolean
49 /**
50 * Include mutations matching this mutation key
51 */
52 mutationKey?: MutationKey
53 /**
54 * Filter by mutation status
55 */
56 status?: MutationStatus
57}
58β
59export type Updater<TInput, TOutput> = TOutput | ((input: TInput) => TOutput)
60β
61export type QueryTypeFilter = 'all' | 'active' | 'inactive'
62β
63// UTILS
64β
65export const isServer = typeof window === 'undefined' || 'Deno' in window
66β
67export function noop(): undefined {
68 return undefined
69}
70β
71export function functionalUpdate<TInput, TOutput>(
72 updater: Updater<TInput, TOutput>,
73 input: TInput,
74): TOutput {
75 return typeof updater === 'function'
76 ? (updater as (_: TInput) => TOutput)(input)
77 : updater
78}
79β
80export function isValidTimeout(value: unknown): value is number {
81 return typeof value === 'number' && value >= 0 && value !== Infinity
82}
83β
84export function timeUntilStale(updatedAt: number, staleTime?: number): number {
85 return Math.max(updatedAt + (staleTime || 0) - Date.now(), 0)
86}
87β
88export function matchQuery(
89 filters: QueryFilters,
90 query: Query<any, any, any, any>,
91): boolean {
92 const {
93 type = 'all',
94 exact,
95 fetchStatus,
96 predicate,
97 queryKey,
98 stale,
99 } = filters
100β
101 if (queryKey) {
102 if (exact) {
103 if (query.queryHash !== hashQueryKeyByOptions(queryKey, query.options)) {
104 return false
105 }
106 } else if (!partialMatchKey(query.queryKey, queryKey)) {
107 return false
108 }
109 }
110β
111 if (type !== 'all') {
112 const isActive = query.isActive()
113 if (type === 'active' && !isActive) {
114 return false
115 }
116 if (type === 'inactive' && isActive) {
117 return false
118 }
119 }
120β
121 if (typeof stale === 'boolean' && query.isStale() !== stale) {
122 return false
123 }
124β
125 if (
126 typeof fetchStatus !== 'undefined' &&
127 fetchStatus !== query.state.fetchStatus
128 ) {
129 return false
130 }
131β
132 if (predicate && !predicate(query)) {
133 return false
134 }
135β
136 return true
137}
138β
139export function matchMutation(
140 filters: MutationFilters,
141 mutation: Mutation<any, any>,
142): boolean {
143 const { exact, status, predicate, mutationKey } = filters
144 if (mutationKey) {
145 if (!mutation.options.mutationKey) {
146 return false
147 }
148 if (exact) {
149 if (hashKey(mutation.options.mutationKey) !== hashKey(mutationKey)) {
150 return false
151 }
152 } else if (!partialMatchKey(mutation.options.mutationKey, mutationKey)) {
153 return false
154 }
155 }
156β
157 if (status && mutation.state.status !== status) {
158 return false
159 }
160β
161 if (predicate && !predicate(mutation)) {
162 return false
163 }
164β
165 return true
166}
167β
168export function hashQueryKeyByOptions<TQueryKey extends QueryKey = QueryKey>(
169 queryKey: TQueryKey,
170 options?: QueryOptions<any, any, any, TQueryKey>,
171): string {
172 const hashFn = options?.queryKeyHashFn || hashKey
173 return hashFn(queryKey)
174}
175β
176/**
177 * Default query & mutation keys hash function.
178 * Hashes the value into a stable hash.
179 */
180export function hashKey(queryKey: QueryKey | MutationKey): string {
181 return JSON.stringify(queryKey, (_, val) =>
182 isPlainObject(val)
183 ? Object.keys(val)
184 .sort()
185 .reduce((result, key) => {
186 result[key] = val[key]
187 return result
188 }, {} as any)
189 : val,
190 )
191}
192β
193/**
194 * Checks if key `b` partially matches with key `a`.
195 */
196export function partialMatchKey(a: QueryKey, b: QueryKey): boolean
197export function partialMatchKey(a: any, b: any): boolean {
198 if (a === b) {
199 return true
200 }
201β
202 if (typeof a !== typeof b) {
203 return false
204 }
205β
206 if (a && b && typeof a === 'object' && typeof b === 'object') {
207 return !Object.keys(b).some((key) => !partialMatchKey(a[key], b[key]))
208 }
209β
210 return false
211}
212β
213/**
214 * This function returns `a` if `b` is deeply equal.
215 * If not, it will replace any deeply equal children of `b` with those of `a`.
216 * This can be used for structural sharing between JSON values for example.
217 */
218export function replaceEqualDeep<T>(a: unknown, b: T): T
219export function replaceEqualDeep(a: any, b: any): any {
220 if (a === b) {
221 return a
222 }
223β
224 const array = isPlainArray(a) && isPlainArray(b)
225β
226 if (array || (isPlainObject(a) && isPlainObject(b))) {
227 const aSize = array ? a.length : Object.keys(a).length
228 const bItems = array ? b : Object.keys(b)
229 const bSize = bItems.length
230 const copy: any = array ? [] : {}
231β
232 let equalItems = 0
233β
234 for (let i = 0; i < bSize; i++) {
235 const key = array ? i : bItems[i]
236 copy[key] = replaceEqualDeep(a[key], b[key])
237 if (copy[key] === a[key]) {
238 equalItems++
239 }
240 }
241β
242 return aSize === bSize && equalItems === aSize ? a : copy
243 }
244β
245 return b
246}
247β
248/**
249 * Shallow compare objects. Only works with objects that always have the same properties.
250 */
251export function shallowEqualObjects<T>(a: T, b: T): boolean {
252 if ((a && !b) || (b && !a)) {
253 return false
254 }
255β
256 for (const key in a) {
257 if (a[key] !== b[key]) {
258 return false
259 }
260 }
261β
262 return true
263}
264β
265export function isPlainArray(value: unknown) {
266 return Array.isArray(value) && value.length === Object.keys(value).length
267}
268β
269// Copied from: https://github.com/jonschlinkert/is-plain-object
270export function isPlainObject(o: any): o is Object {
271 if (!hasObjectPrototype(o)) {
272 return false
273 }
274β
275 // If has modified constructor
276 const ctor = o.constructor
277 if (typeof ctor === 'undefined') {
278 return true
279 }
280β
281 // If has modified prototype
282 const prot = ctor.prototype
283 if (!hasObjectPrototype(prot)) {
284 return false
285 }
286β
287 // If constructor does not have an Object-specific method
288 if (!prot.hasOwnProperty('isPrototypeOf')) {
289 return false
290 }
291β
292 // Most likely a plain Object
293 return true
294}
295β
296function hasObjectPrototype(o: any): boolean {
297 return Object.prototype.toString.call(o) === '[object Object]'
298}
299β
300export function sleep(timeout: number): Promise<void> {
301 return new Promise((resolve) => {
302 setTimeout(resolve, timeout)
303 })
304}
305β
306/**
307 * Schedules a microtask.
308 * This can be useful to schedule state updates after rendering.
309 */
310export function scheduleMicrotask(callback: () => void) {
311 sleep(0).then(callback)
312}
313β
314export function replaceData<
315 TData,
316 TOptions extends QueryOptions<any, any, any, any>,
317>(prevData: TData | undefined, data: TData, options: TOptions): TData {
318 if (typeof options.structuralSharing === 'function') {
319 return options.structuralSharing(prevData, data)
320 } else if (options.structuralSharing !== false) {
321 // Structurally share data between prev and new data if needed
322 return replaceEqualDeep(prevData, data)
323 }
324 return data
325}
326β
327export function keepPreviousData<T>(
328 previousData: T | undefined,
329): T | undefined {
330 return previousData
331}
332β
333export function addToEnd<T>(items: Array<T>, item: T, max = 0): Array<T> {
334 const newItems = [...items, item]
335 return max && newItems.length > max ? newItems.slice(1) : newItems
336}
337β
338export function addToStart<T>(items: Array<T>, item: T, max = 0): Array<T> {
339 const newItems = [item, ...items]
340 return max && newItems.length > max ? newItems.slice(0, -1) : newItems
341}