useOfflineBookingCachePolling.js
2.6 KB
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
import { ref, onMounted, onUnmounted } from 'vue'
import { refresh_offline_booking_cache } from '@/composables/useOfflineBookingCache'
let polling_timer_id = null
let polling_running = false
let polling_in_flight = false
let polling_ref_count = 0
/**
* @description: 刷新离线预约缓存一次
* @param {Object} options 选项
* @param {Boolean} options.force 是否强制刷新
*/
const run_refresh_once = async (options) => {
if (polling_in_flight) return
polling_in_flight = true
try {
await refresh_offline_booking_cache({ force: !!options?.force })
} finally {
polling_in_flight = false
}
}
/**
* @description: 启动离线预约缓存轮询
* @param {Object} options 选项
* @param {Number} options.interval_ms 轮询间隔,单位毫秒
* @param {Boolean} options.immediate 是否立即刷新一次
*/
export const start_offline_booking_cache_polling = (options) => {
const interval_ms = Number(options?.interval_ms || 60000)
if (polling_running) return
polling_running = true
if (options?.immediate !== false) {
run_refresh_once(options)
}
polling_timer_id = setInterval(() => {
run_refresh_once(options)
}, interval_ms)
}
/**
* @description: 停止离线预约缓存轮询
*/
export const stop_offline_booking_cache_polling = () => {
if (!polling_timer_id) {
polling_running = false
return
}
clearInterval(polling_timer_id)
polling_timer_id = null
polling_running = false
}
/**
* @description: 用于管理离线预约缓存轮询的组合式函数
* @param {Object} options 选项
* @param {Boolean} options.enabled 是否启用轮询
* @param {Boolean} options.auto 是否自动启动轮询
* @param {Number} options.interval_ms 轮询间隔,单位毫秒
* @param {Boolean} options.immediate 是否立即刷新一次
*/
export const use_offline_booking_cache_polling = (options) => {
const is_running = ref(false)
const enabled = options?.enabled !== false
const start = () => {
if (!enabled) return
polling_ref_count += 1
start_offline_booking_cache_polling(options)
is_running.value = true
}
const stop = () => {
if (!is_running.value) return
polling_ref_count = Math.max(0, polling_ref_count - 1)
if (polling_ref_count === 0) {
stop_offline_booking_cache_polling()
}
is_running.value = false
}
onMounted(() => {
if (options?.auto !== false) start()
})
onUnmounted(() => {
stop()
})
return {
is_running,
start,
stop,
}
}