UNPKG

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