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

utils.ts

85 lines2.2 KB

1import type {
2 ParseFilterArgs,
3 ParseQueryArgs,
4 SolidQueryFilters,
5 SolidQueryKey,
6} from './types'
7import type { QueryFunction, QueryOptions } from '@tanstack/query-core'
8​
9export function isQueryKey(value: unknown): value is SolidQueryKey {
10 return typeof value === 'function'
12​
13// The parseQuery Args functions helps normalize the arguments into the correct form.
14// Whatever the parameters are, they are normalized into the correct form.
15export function parseQueryArgs<
16 TOptions extends Omit<
17 QueryOptions<any, any, any, ReturnType<TQueryKey>>,
18 'queryKey'
19 > & {
20 queryKey?: TQueryKey
21 },
22 TQueryKey extends () => readonly unknown[] = SolidQueryKey,
23>(
24 arg1: TQueryKey | TOptions,
25 arg2?: QueryFunction<any, ReturnType<TQueryKey>> | TOptions,
26 arg3?: TOptions,
27): ParseQueryArgs<TOptions, TQueryKey> {
28 if (!isQueryKey(arg1)) {
29 const { queryKey: solidKey, ...opts } = arg1 as any
30 if (solidKey) {
31 return {
32 ...opts,
33 queryKey: solidKey(),
34 }
35 }
36 return arg1 as any
37 }
38​
39 if (typeof arg2 === 'function') {
40 return { ...arg3, queryKey: arg1(), queryFn: arg2 } as any
41 }
42​
43 return { ...arg2, queryKey: arg1() } as any
45​
46export function parseFilterArgs<
47 TFilters extends SolidQueryFilters,
48 TOptions = unknown,
49>(
50 arg1?: SolidQueryKey | TFilters,
51 arg2?: TFilters | TOptions,
52 arg3?: TOptions,
53): [ParseFilterArgs<TFilters>, TOptions | undefined] {
54 return (
55 isQueryKey(arg1)
56 ? [{ ...arg2, queryKey: arg1() }, arg3]
57 : [{ ...arg1, queryKey: arg1?.queryKey?.() }, arg2]
58 ) as [ParseFilterArgs<TFilters>, TOptions]
60​
61export function shouldThrowError<T extends (...args: any[]) => boolean>(
62 _useErrorBoundary: boolean | T | undefined,
63 params: Parameters<T>,
64): boolean {
65 // Allow useErrorBoundary function to override throwing behavior on a per-error basis
66 if (typeof _useErrorBoundary === 'function') {
67 return _useErrorBoundary(...params)
68 }
69​
70 return !!_useErrorBoundary
72​
73export function sleep(timeout: number): Promise<void> {
74 return new Promise((resolve) => {
75 setTimeout(resolve, timeout)
76 })
78​
79/**
80 * Schedules a microtask.
81 * This can be useful to schedule state updates after rendering.
82 */
83export function scheduleMicrotask(callback: () => void) {
84 sleep(0).then(callback)