-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathuse-condition-watcher.ts
342 lines (310 loc) · 10.3 KB
/
use-condition-watcher.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
import { Conditions, Config, Mutate, UseConditionWatcherReturn } from './types'
import {
UnwrapNestedRefs,
computed,
getCurrentInstance,
isRef,
onUnmounted,
reactive,
readonly,
ref,
shallowRef,
unref,
watch,
watchEffect,
} from 'vue-demi'
import { containsProp, isNoData as isDataEmpty, isObject, isServer, rAF } from 'vue-condition-watcher/_internal'
import { createEvents, useCache, useHistory, usePromiseQueue } from 'vue-condition-watcher/_internal'
import {
createParams,
deepClone,
filterNoneValueObject,
isEquivalent,
pick,
syncQuery2Conditions,
} from 'vue-condition-watcher/_internal'
export default function useConditionWatcher<Cond extends Record<string, any>, Result, AfterFetchResult = Result>(
config: Config<Cond, Result, AfterFetchResult>
): UseConditionWatcherReturn<Cond, AfterFetchResult extends Result ? Result : AfterFetchResult> {
function isFetchConfig(obj: Record<string, any>): obj is typeof config {
return containsProp(
obj,
'fetcher',
'conditions',
'defaultParams',
'initialData',
'manual',
'immediate',
'history',
'pollingInterval',
'pollingWhenHidden',
'pollingWhenOffline',
'revalidateOnFocus',
'cacheProvider',
'beforeFetch',
'afterFetch',
'onFetchError'
)
}
function isHistoryOption() {
if (!config.history || !config.history.sync) return false
return containsProp(config.history, 'navigation', 'ignore', 'sync')
}
// default config
let watcherConfig: typeof config = {
fetcher: config.fetcher,
conditions: config.conditions,
immediate: true,
manual: false,
initialData: undefined,
pollingInterval: isRef(config.pollingInterval) ? config.pollingInterval : ref(config.pollingInterval || 0),
pollingWhenHidden: false,
pollingWhenOffline: false,
revalidateOnFocus: false,
cacheProvider: () => new Map(),
}
// update config
if (isFetchConfig(config)) {
watcherConfig = { ...watcherConfig, ...config }
}
const cache = useCache(watcherConfig.fetcher, watcherConfig.cacheProvider())
const backupIntiConditions = deepClone(watcherConfig.conditions)
const _conditions = reactive<Cond>(watcherConfig.conditions)
const isFetching = ref(false)
const isOnline = ref(true)
const isActive = ref(true)
const data = shallowRef(
cache.cached(backupIntiConditions) ? cache.get(backupIntiConditions) : watcherConfig.initialData || undefined
)
const error = ref(undefined)
const query = ref({})
const pollingTimer = ref()
const { enqueue } = usePromiseQueue()
// - create fetch event & condition event & web event
const {
conditionEvent,
responseEvent,
errorEvent,
finallyEvent,
reconnectEvent,
focusEvent,
visibilityEvent,
stopFocusEvent,
stopReconnectEvent,
stopVisibilityEvent,
} = createEvents()
const resetConditions = (cond?: Record<string, any>): void => {
const conditionKeys = Object.keys(_conditions)
Object.assign(_conditions, isObject(cond) ? pick(cond, conditionKeys) : backupIntiConditions)
}
const isLoading = computed(() => !error.value && !data.value)
const conditionsChangeHandler = async (conditions, throwOnFailed = false) => {
const checkThrowOnFailed = typeof throwOnFailed === 'boolean' ? throwOnFailed : false
if (isFetching.value) return
isFetching.value = true
error.value = undefined
const conditions2Object: Conditions<Cond> = conditions
let customConditions: Record<string, any> = {}
const deepCopyCondition: Conditions<Cond> = deepClone(conditions2Object)
if (typeof watcherConfig.beforeFetch === 'function') {
let isCanceled = false
customConditions = await watcherConfig.beforeFetch(deepCopyCondition, () => {
isCanceled = true
})
if (isCanceled) {
isFetching.value = false
return Promise.resolve(undefined)
}
if (!customConditions || typeof customConditions !== 'object' || customConditions.constructor !== Object) {
isFetching.value = false
throw new Error(`[vue-condition-watcher]: beforeFetch should return an object`)
}
}
const validateCustomConditions: boolean = Object.keys(customConditions).length !== 0
/*
* if custom conditions has value, just use custom conditions
* filterNoneValueObject will filter no value like [] , '', null, undefined
* example. {name: '', items: [], age: 0, tags: null}
* return result will be {age: 0}
*/
query.value = filterNoneValueObject(validateCustomConditions ? customConditions : conditions2Object)
const finalConditions: Record<string, any> = createParams(query.value, watcherConfig.defaultParams)
let responseData: any = undefined
data.value = cache.cached(query.value) ? cache.get(query.value) : watcherConfig.initialData || undefined
return new Promise((resolve, reject) => {
config
.fetcher(finalConditions)
.then(async (fetchResponse) => {
responseData = fetchResponse
if (typeof watcherConfig.afterFetch === 'function') {
responseData = await watcherConfig.afterFetch(fetchResponse)
}
if (responseData === undefined) {
console.warn(`[vue-condition-watcher]: "afterFetch" return value is ${responseData}. Please check it.`)
}
if (!isEquivalent(data.value, responseData)) {
data.value = responseData
}
if (!isEquivalent(cache.get(query.value), responseData)) {
cache.set(query.value, responseData)
}
responseEvent.trigger(responseData)
return resolve(fetchResponse)
})
.catch(async (fetchError) => {
if (typeof watcherConfig.onFetchError === 'function') {
;({ data: responseData, error: fetchError } = await watcherConfig.onFetchError({
data: undefined,
error: fetchError,
}))
data.value = responseData || watcherConfig.initialData
error.value = fetchError
}
errorEvent.trigger(fetchError)
if (checkThrowOnFailed) {
return reject(fetchError)
}
return resolve(undefined)
})
.finally(() => {
isFetching.value = false
finallyEvent.trigger()
})
})
}
const revalidate = (throwOnFailed = false) =>
enqueue(() => conditionsChangeHandler({ ..._conditions }, throwOnFailed))
function execute(throwOnFailed = false) {
if (isDataEmpty(data.value) || isServer) {
revalidate(throwOnFailed)
} else {
rAF(() => revalidate(throwOnFailed))
}
}
// - Start polling with out setting to manual
if (!watcherConfig.manual) {
watchEffect((onCleanup) => {
const pollingInterval = unref(watcherConfig.pollingInterval)
if (pollingInterval) {
pollingTimer.value = (() => {
let timerId = null
function next() {
const interval = pollingInterval
if (interval && timerId !== -1) {
timerId = setTimeout(nun, interval)
}
}
function nun() {
// Only run when the page is visible, online and not errored.
if (
!error.value &&
(watcherConfig.pollingWhenHidden || isActive.value) &&
(watcherConfig.pollingWhenOffline || isOnline.value)
) {
revalidate().then(next)
} else {
next()
}
}
next()
return () => timerId && clearTimeout(timerId)
})()
}
onCleanup(() => {
pollingTimer.value && pollingTimer.value()
})
})
}
// - mutate: Modify `data` directly
// - `data` is read only by default, recommend modify `data` at `afterFetch`
// - When you need to modify `data`, you can use mutate() to directly modify data
/*
* Two way to use mutate
* - 1.
* mutate(newData)
* - 2.
* mutate((draft) => {
* draft[0].name = 'runkids'
* return draft
* })
*/
const mutate = (...args): Mutate<Result> => {
const arg = args[0]
if (arg === undefined) {
return data.value
}
if (typeof arg === 'function') {
data.value = arg(deepClone(data.value))
} else {
data.value = arg
}
cache.set({ ..._conditions }, data.value)
return data.value
}
// - History mode base on vue-router
if (isHistoryOption()) {
const historyOption = {
sync: config.history.sync,
ignore: config.history.ignore || [],
navigation: config.history.navigation || 'push',
listener(parsedQuery: Record<string, any>) {
const queryObject = Object.keys(parsedQuery).length ? parsedQuery : backupIntiConditions
syncQuery2Conditions(_conditions, queryObject, backupIntiConditions)
},
}
useHistory(query, historyOption)
}
// - Automatic data fetching by default
if (!watcherConfig.manual && watcherConfig.immediate) {
execute()
}
watch(
() => ({ ..._conditions }),
(nc, oc) => {
// - Deep check object if be true do nothing
if (isEquivalent(nc, oc)) return
conditionEvent.trigger(deepClone(nc), deepClone(oc))
// - Automatic data fetching until manual to be false
!watcherConfig.manual && enqueue(() => conditionsChangeHandler(nc))
}
)
reconnectEvent.on((status: boolean) => {
isOnline.value = status
})
visibilityEvent.on((status: boolean) => {
isActive.value = status
})
const stopSubscribeFocus = focusEvent.on(() => {
if (!isActive.value) return
execute()
// if (isHistoryOption() && cache.cached({ ..._conditions })) {
//todo sync to query
// }
})
if (!watcherConfig.revalidateOnFocus) {
stopFocusEvent()
stopSubscribeFocus.off()
}
if (getCurrentInstance()) {
onUnmounted(() => {
pollingTimer.value && pollingTimer.value()
stopFocusEvent()
stopReconnectEvent()
stopVisibilityEvent()
})
}
return {
conditions: _conditions as UnwrapNestedRefs<Cond>,
data: readonly(data),
error: readonly(error),
isFetching: readonly(isFetching),
isLoading,
execute,
mutate,
resetConditions,
onConditionsChange: conditionEvent.on,
onFetchSuccess: responseEvent.on,
onFetchError: errorEvent.on,
onFetchFinally: finallyEvent.on,
}
}