Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

utils.ts

345 lines7.8 KB

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