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

utils.ts

83 lines2.1 KB

1/* eslint-disable @typescript-eslint/no-explicit-any */
2import { isRef, unref } from 'vue-demi'
3import type { MutationKey, QueryKey } from '@tanstack/query-core'
4import type { UnwrapRef } from 'vue-demi'
5​
6export const VUE_QUERY_CLIENT = 'VUE_QUERY_CLIENT'
7​
8export function getClientKey(key?: string) {
9 const suffix = key ? `:${key}` : ''
10 return `${VUE_QUERY_CLIENT}${suffix}`
12​
13export function isQueryKey(value: unknown): value is QueryKey {
14 return Array.isArray(value)
16​
17export function isMutationKey(value: unknown): value is MutationKey {
18 return Array.isArray(value)
20​
21export function updateState(
22 state: Record<string, unknown>,
23 update: Record<string, any>,
24): void {
25 Object.keys(state).forEach((key) => {
26 state[key] = update[key]
27 })
29​
30export function cloneDeep<T>(
31 value: T,
32 customizer?: (val: unknown) => unknown | void,
33): T {
34 if (customizer) {
35 const result = customizer(value)
36 if (result !== undefined || isRef(value)) {
37 return result as typeof value
38 }
39 }
40​
41 if (Array.isArray(value)) {
42 return value.map((val) => cloneDeep(val, customizer)) as typeof value
43 }
44​
45 if (typeof value === 'object' && isPlainObject(value)) {
46 const entries = Object.entries(value).map(([key, val]) => [
47 key,
48 cloneDeep(val, customizer),
49 ])
50 return Object.fromEntries(entries)
51 }
52​
53 return value
55​
56export function cloneDeepUnref<T>(obj: T): UnwrapRef<T> {
57 return cloneDeep(obj, (val) => {
58 if (isRef(val)) {
59 return cloneDeepUnref(unref(val))
60 }
61 }) as UnwrapRef<typeof obj>
63​
64function isPlainObject(value: unknown): value is Object {
65 if (Object.prototype.toString.call(value) !== '[object Object]') {
66 return false
67 }
68​
69 const prototype = Object.getPrototypeOf(value)
70 return prototype === null || prototype === Object.prototype
72​
73export function shouldThrowError<T extends (...args: any[]) => boolean>(
74 _useErrorBoundary: boolean | T | undefined,
75 params: Parameters<T>,
76): boolean {
77 // Allow useErrorBoundary function to override throwing behavior on a per-error basis
78 if (typeof _useErrorBoundary === 'function') {
79 return _useErrorBoundary(...params)
80 }
81​
82 return !!_useErrorBoundary