UNPKG

2.43 kBJavaScriptView Raw
1import deepEqual from 'fast-deep-equal';
2import isDocumentVisible from './libs/is-document-visible';
3import isOnline from './libs/is-online';
4import Cache from './cache';
5// cache
6const cache = new Cache();
7// state managers
8const CONCURRENT_PROMISES = {};
9const CONCURRENT_PROMISES_TS = {};
10const FOCUS_REVALIDATORS = {};
11const CACHE_REVALIDATORS = {};
12const MUTATION_TS = {};
13// error retry
14function onErrorRetry(_, __, config, revalidate, opts) {
15 if (!isDocumentVisible()) {
16 // if it's hidden, stop
17 // it will auto revalidate when focus
18 return;
19 }
20 if (config.errorRetryCount && opts.retryCount > config.errorRetryCount) {
21 return;
22 }
23 // exponential backoff
24 const count = Math.min(opts.retryCount || 0, 8);
25 const timeout = ~~((Math.random() + 0.5) * (1 << count)) * config.errorRetryInterval;
26 setTimeout(revalidate, timeout, opts);
27}
28// client side: need to adjust the config
29// based on the browser status
30// slow connection (<= 70Kbps)
31const slowConnection = typeof window !== 'undefined' &&
32 navigator['connection'] &&
33 ['slow-2g', '2g'].indexOf(navigator['connection'].effectiveType) !== -1;
34// config
35const defaultConfig = {
36 // events
37 onLoadingSlow: () => { },
38 onSuccess: () => { },
39 onError: () => { },
40 onErrorRetry,
41 errorRetryInterval: (slowConnection ? 10 : 5) * 1000,
42 focusThrottleInterval: 5 * 1000,
43 dedupingInterval: 2 * 1000,
44 loadingTimeout: (slowConnection ? 5 : 3) * 1000,
45 refreshInterval: 0,
46 revalidateOnFocus: true,
47 revalidateOnReconnect: true,
48 refreshWhenHidden: false,
49 refreshWhenOffline: false,
50 shouldRetryOnError: true,
51 suspense: false,
52 compare: deepEqual
53};
54// Focus revalidate
55let eventsBinded = false;
56if (typeof window !== 'undefined' && window.addEventListener && !eventsBinded) {
57 const revalidate = () => {
58 if (!isDocumentVisible() || !isOnline())
59 return;
60 for (let key in FOCUS_REVALIDATORS) {
61 if (FOCUS_REVALIDATORS[key][0])
62 FOCUS_REVALIDATORS[key][0]();
63 }
64 };
65 window.addEventListener('visibilitychange', revalidate, false);
66 window.addEventListener('focus', revalidate, false);
67 // only bind the events once
68 eventsBinded = true;
69}
70export { CONCURRENT_PROMISES, CONCURRENT_PROMISES_TS, FOCUS_REVALIDATORS, CACHE_REVALIDATORS, MUTATION_TS, cache };
71export default defaultConfig;