UNPKG

vue-admin-core

Version:
58 lines (55 loc) 1.5 kB
import { watch, toRef, toValue } from 'vue'; import subscribeReVisible, { isDocumentVisible } from '../../__utils__/subscribeReVisible.mjs'; const usePollingPlugin = (fetchInstance, { pollingInterval, pollingWhenHidden = true, pollingErrorRetryCount = -1 }) => { let timer = null; let count = 0; let unsubscribe = () => { }; const stopPolling = () => { if (timer) { clearTimeout(timer); } if (unsubscribe) unsubscribe(); }; watch(toRef(pollingInterval), () => { if (!toValue(pollingInterval)) { stopPolling(); } }); if (!pollingInterval) { return {}; } return { onBefore: () => { stopPolling(); }, onError: () => { count += 1; }, onSuccess: () => { count = 0; }, onFinally: () => { if (pollingErrorRetryCount === -1 || // When an error occurs, the request is not repeated after pollingErrorRetryCount retries pollingErrorRetryCount !== -1 && count <= pollingErrorRetryCount) { timer = setTimeout(() => { if (!pollingWhenHidden && !isDocumentVisible()) { unsubscribe = subscribeReVisible(() => { fetchInstance.refresh(); }); } else { fetchInstance.refresh(); } }, toValue(pollingInterval)); } else { count = 0; } }, onCancel: () => { stopPolling(); } }; }; export { usePollingPlugin as default }; //# sourceMappingURL=usePollingPlugin.mjs.map