1 | import isDocumentVisible from './libs/is-document-visible';
|
2 | import isOnline from './libs/is-online';
|
3 |
|
4 | const __cache = new Map();
|
5 | function cacheGet(key) {
|
6 | return __cache.get(key);
|
7 | }
|
8 | function cacheSet(key, value) {
|
9 | return __cache.set(key, value);
|
10 | }
|
11 | function cacheClear() {
|
12 | __cache.clear();
|
13 | }
|
14 |
|
15 | const CONCURRENT_PROMISES = {};
|
16 | const CONCURRENT_PROMISES_TS = {};
|
17 | const FOCUS_REVALIDATORS = {};
|
18 | const CACHE_REVALIDATORS = {};
|
19 | const MUTATION_TS = {};
|
20 |
|
21 | function onErrorRetry(_, __, config, revalidate, opts) {
|
22 | if (!isDocumentVisible()) {
|
23 |
|
24 |
|
25 | return;
|
26 | }
|
27 |
|
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 |
|
33 | const defaultConfig = {
|
34 |
|
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 | };
|
51 | if (typeof window !== 'undefined') {
|
52 |
|
53 |
|
54 |
|
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 |
|
63 | let eventsBinded = false;
|
64 | if (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 |
|
76 | eventsBinded = true;
|
77 | }
|
78 | export { CONCURRENT_PROMISES, CONCURRENT_PROMISES_TS, FOCUS_REVALIDATORS, CACHE_REVALIDATORS, MUTATION_TS, cacheGet, cacheSet, cacheClear };
|
79 | export default defaultConfig;
|