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 aItems = array ? a : Object.keys(a)
228 const aSize = aItems.length
229 const bItems = array ? b : Object.keys(b)
230 const bSize = bItems.length
231 const copy: any = array ? [] : {}
232β
233 let equalItems = 0
234β
235 for (let i = 0; i < bSize; i++) {
236 const key = array ? i : bItems[i]
237 if (
238 !array &&
239 a[key] === undefined &&
240 b[key] === undefined &&
241 aItems.includes(key)
242 ) {
243 copy[key] = undefined
244 equalItems++
245 } else {
246 copy[key] = replaceEqualDeep(a[key], b[key])
247 if (copy[key] === a[key] && a[key] !== undefined) {
248 equalItems++
249 }
250 }
251 }
252β
253 return aSize === bSize && equalItems === aSize ? a : copy
254 }
255β
256 return b
257}
258β
259/**
260 * Shallow compare objects. Only works with objects that always have the same properties.
261 */
262export function shallowEqualObjects<T>(a: T, b: T): boolean {
263 if ((a && !b) || (b && !a)) {
264 return false
265 }
266β
267 for (const key in a) {
268 if (a[key] !== b[key]) {
269 return false
270 }
271 }
272β
273 return true
274}
275β
276export function isPlainArray(value: unknown) {
277 return Array.isArray(value) && value.length === Object.keys(value).length
278}
279β
280// Copied from: https://github.com/jonschlinkert/is-plain-object
281export function isPlainObject(o: any): o is Object {
282 if (!hasObjectPrototype(o)) {
283 return false
284 }
285β
286 // If has no constructor
287 const ctor = o.constructor
288 if (typeof ctor === 'undefined') {
289 return true
290 }
291β
292 // If has modified prototype
293 const prot = ctor.prototype
294 if (!hasObjectPrototype(prot)) {
295 return false
296 }
297β
298 // If constructor does not have an Object-specific method
299 if (!prot.hasOwnProperty('isPrototypeOf')) {
300 return false
301 }
302β
303 // Most likely a plain Object
304 return true
305}
306β
307function hasObjectPrototype(o: any): boolean {
308 return Object.prototype.toString.call(o) === '[object Object]'
309}
310β
311export function sleep(ms: number): Promise<void> {
312 return new Promise((resolve) => {
313 setTimeout(resolve, ms)
314 })
315}
316β
317export function replaceData<
318 TData,
319 TOptions extends QueryOptions<any, any, any, any>,
320>(prevData: TData | undefined, data: TData, options: TOptions): TData {
321 if (typeof options.structuralSharing === 'function') {
322 return options.structuralSharing(prevData, data)
323 } else if (options.structuralSharing !== false) {
324 // Structurally share data between prev and new data if needed
325 return replaceEqualDeep(prevData, data)
326 }
327 return data
328}
329β
330export function keepPreviousData<T>(
331 previousData: T | undefined,
332): T | undefined {
333 return previousData
334}
335β
336export function addToEnd<T>(items: Array<T>, item: T, max = 0): Array<T> {
337 const newItems = [...items, item]
338 return max && newItems.length > max ? newItems.slice(1) : newItems
339}
340β
341export function addToStart<T>(items: Array<T>, item: T, max = 0): Array<T> {
342 const newItems = [item, ...items]
343 return max && newItems.length > max ? newItems.slice(0, -1) : newItems
344}