forked from vuejs/apollo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathloadingTracking.ts
93 lines (78 loc) · 2.13 KB
/
loadingTracking.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import { Ref, watch, ref, getCurrentScope, onScopeDispose } from 'vue-demi'
import { isServer } from './env.js'
import type { EffectScope } from 'vue-demi'
export interface LoadingTracking {
queries: Ref<number>
mutations: Ref<number>
subscriptions: Ref<number>
}
export interface AppLoadingTracking extends LoadingTracking {
components: Map<EffectScope, LoadingTracking>
}
export const globalTracking: AppLoadingTracking = {
queries: ref(0),
mutations: ref(0),
subscriptions: ref(0),
components: new Map(),
}
export function getCurrentTracking () {
const currentScope = getCurrentScope()
if (!currentScope) {
return {}
}
let tracking: LoadingTracking
if (isServer) {
// SSR does not support onScopeDispose, so if we don't skip this, it will leak memory
tracking = {
queries: ref(0),
mutations: ref(0),
subscriptions: ref(0),
}
return { tracking }
}
if (!globalTracking.components.has(currentScope)) {
// Add per-component tracking
globalTracking.components.set(currentScope, tracking = {
queries: ref(0),
mutations: ref(0),
subscriptions: ref(0),
})
// Cleanup
onScopeDispose(() => {
globalTracking.components.delete(currentScope)
})
} else {
tracking = globalTracking.components.get(currentScope) as LoadingTracking
}
return {
tracking,
}
}
function track (loading: Ref<boolean>, type: keyof LoadingTracking) {
if (isServer) return
const { tracking } = getCurrentTracking()
watch(loading, (value, oldValue) => {
if (oldValue != null && value !== oldValue) {
const mod = value ? 1 : -1
if (tracking) tracking[type].value += mod
globalTracking[type].value += mod
}
}, {
immediate: true,
})
onScopeDispose(() => {
if (loading.value) {
if (tracking) tracking[type].value--
globalTracking[type].value--
}
})
}
export function trackQuery (loading: Ref<boolean>) {
track(loading, 'queries')
}
export function trackMutation (loading: Ref<boolean>) {
track(loading, 'mutations')
}
export function trackSubscription (loading: Ref<boolean>) {
track(loading, 'subscriptions')
}