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 globalThis
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 (fetchStatus && fetchStatus !== query.state.fetchStatus) {
126 return false
127 }
128β
129 if (predicate && !predicate(query)) {
130 return false
131 }
132β
133 return true
134}
135β
136export function matchMutation(
137 filters: MutationFilters,
138 mutation: Mutation<any, any>,
139): boolean {
140 const { exact, status, predicate, mutationKey } = filters
141 if (mutationKey) {
142 if (!mutation.options.mutationKey) {
143 return false
144 }
145 if (exact) {
146 if (hashKey(mutation.options.mutationKey) !== hashKey(mutationKey)) {
147 return false
148 }
149 } else if (!partialMatchKey(mutation.options.mutationKey, mutationKey)) {
150 return false
151 }
152 }
153β
154 if (status && mutation.state.status !== status) {
155 return false
156 }
157β
158 if (predicate && !predicate(mutation)) {
159 return false
160 }
161β
162 return true
163}
164β
165export function hashQueryKeyByOptions<TQueryKey extends QueryKey = QueryKey>(
166 queryKey: TQueryKey,
167 options?: Pick<QueryOptions<any, any, any, any>, 'queryKeyHashFn'>,
168): string {
169 const hashFn = options?.queryKeyHashFn || hashKey
170 return hashFn(queryKey)
171}
172β
173/**
174 * Default query & mutation keys hash function.
175 * Hashes the value into a stable hash.
176 */
177export function hashKey(queryKey: QueryKey | MutationKey): string {
178 return JSON.stringify(queryKey, (_, val) =>
179 isPlainObject(val)
180 ? Object.keys(val)
181 .sort()
182 .reduce((result, key) => {
183 result[key] = val[key]
184 return result
185 }, {} as any)
186 : val,
187 )
188}
189β
190/**
191 * Checks if key `b` partially matches with key `a`.
192 */
193export function partialMatchKey(a: QueryKey, b: QueryKey): boolean
194export function partialMatchKey(a: any, b: any): boolean {
195 if (a === b) {
196 return true
197 }
198β
199 if (typeof a !== typeof b) {
200 return false
201 }
202β
203 if (a && b && typeof a === 'object' && typeof b === 'object') {
204 return !Object.keys(b).some((key) => !partialMatchKey(a[key], b[key]))
205 }
206β
207 return false
208}
209β
210/**
211 * This function returns `a` if `b` is deeply equal.
212 * If not, it will replace any deeply equal children of `b` with those of `a`.
213 * This can be used for structural sharing between JSON values for example.
214 */
215export function replaceEqualDeep<T>(a: unknown, b: T): T
216export function replaceEqualDeep(a: any, b: any): any {
217 if (a === b) {
218 return a
219 }
220β
221 const array = isPlainArray(a) && isPlainArray(b)
222β
223 if (array || (isPlainObject(a) && isPlainObject(b))) {
224 const aItems = array ? a : Object.keys(a)
225 const aSize = aItems.length
226 const bItems = array ? b : Object.keys(b)
227 const bSize = bItems.length
228 const copy: any = array ? [] : {}
229β
230 let equalItems = 0
231β
232 for (let i = 0; i < bSize; i++) {
233 const key = array ? i : bItems[i]
234 if (
235 !array &&
236 a[key] === undefined &&
237 b[key] === undefined &&
238 aItems.includes(key)
239 ) {
240 copy[key] = undefined
241 equalItems++
242 } else {
243 copy[key] = replaceEqualDeep(a[key], b[key])
244 if (copy[key] === a[key] && a[key] !== undefined) {
245 equalItems++
246 }
247 }
248 }
249β
250 return aSize === bSize && equalItems === aSize ? a : copy
251 }
252β
253 return b
254}
255β
256/**
257 * Shallow compare objects.
258 */
259export function shallowEqualObjects<T extends Record<string, any>>(
260 a: T,
261 b: T | undefined,
262): boolean {
263 if (!b || Object.keys(a).length !== Object.keys(b).length) {
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 (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) as TData
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}
345β
346export const skipToken = Symbol()
347export type SkipToken = typeof skipToken