Open History to see the last commit
1import { isRef, unref } from 'vue-demi'
2import type { MaybeRefDeep } from './types'
3β
4export const VUE_QUERY_CLIENT = 'VUE_QUERY_CLIENT'
5β
6export function getClientKey(key?: string) {
7 const suffix = key ? `:${key}` : ''
8 return `${VUE_QUERY_CLIENT}${suffix}`
9}
10β
11export function updateState(
12 state: Record<string, any>,
13 update: Record<string, any>,
14): void {
15 Object.keys(state).forEach((key) => {
16 state[key] = update[key]
17 })
18}
19β
20// Helper function for cloning deep objects where
21// the level and key is provided to the callback function.
22function _cloneDeep<T>(
23 value: MaybeRefDeep<T>,
24 customize?: (
25 val: MaybeRefDeep<T>,
26 key: string,
27 level: number,
28 ) => T | undefined,
29 currentKey: string = '',
30 currentLevel: number = 0,
31): T {
32 if (customize) {
33 const result = customize(value, currentKey, currentLevel)
34 if (result === undefined && isRef(value)) {
35 return result as T
36 }
37 if (result !== undefined) {
38 return result
39 }
40 }
41β
42 if (Array.isArray(value)) {
43 return value.map((val, index) =>
44 _cloneDeep(val, customize, String(index), currentLevel + 1),
45 ) as unknown as T
46 }
47β
48 if (typeof value === 'object' && isPlainObject(value)) {
49 const entries = Object.entries(value).map(([key, val]) => [
50 key,
51 _cloneDeep(val, customize, key, currentLevel + 1),
52 ])
53 return Object.fromEntries(entries)
54 }
55β
56 return value as T
57}
58β
59export function cloneDeep<T>(
60 value: MaybeRefDeep<T>,
61 customize?: (
62 val: MaybeRefDeep<T>,
63 key: string,
64 level: number,
65 ) => T | undefined,
66): T {
67 return _cloneDeep(value, customize)
68}
69β
70export function cloneDeepUnref<T>(
71 obj: MaybeRefDeep<T>,
72 unrefGetters = false,
73): T {
74 return cloneDeep(obj, (val, key, level) => {
75 // Check if we're at the top level and the key is 'queryKey'
76 //
77 // If so, take the recursive descent where we resolve
78 // getters to values as well as refs.
79 if (level === 1 && key === 'queryKey') {
80 return cloneDeepUnref(val, true)
81 }
82β
83 // Resolve getters to values if specified.
84 if (unrefGetters && isFunction(val)) {
85 // Cast due to older TS versions not allowing calling
86 // on certain intersection types.
87 return cloneDeepUnref((val as Function)(), unrefGetters)
88 }
89β
90 // Unref refs and continue to recurse into the value.
91 if (isRef(val)) {
92 return cloneDeepUnref(unref(val), unrefGetters)
93 }
94β
95 return undefined
96 })
97}
98β
99// eslint-disable-next-line @typescript-eslint/no-wrapper-object-types
100function isPlainObject(value: unknown): value is Object {
101 if (Object.prototype.toString.call(value) !== '[object Object]') {
102 return false
103 }
104β
105 const prototype = Object.getPrototypeOf(value)
106 return prototype === null || prototype === Object.prototype
107}
108β
109function isFunction(value: unknown): value is Function {
110 return typeof value === 'function'
111}