1 | import deepEqual from 'fast-deep-equal';
|
2 | import isDocumentVisible from './libs/is-document-visible';
|
3 | import isOnline from './libs/is-online';
|
4 | import Cache from './cache';
|
5 |
|
6 | const cache = new Cache();
|
7 |
|
8 | const CONCURRENT_PROMISES = {};
|
9 | const CONCURRENT_PROMISES_TS = {};
|
10 | const FOCUS_REVALIDATORS = {};
|
11 | const CACHE_REVALIDATORS = {};
|
12 | const MUTATION_TS = {};
|
13 |
|
14 | function onErrorRetry(_, __, config, revalidate, opts) {
|
15 | if (!isDocumentVisible()) {
|
16 |
|
17 |
|
18 | return;
|
19 | }
|
20 | if (config.errorRetryCount && opts.retryCount > config.errorRetryCount) {
|
21 | return;
|
22 | }
|
23 |
|
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 |
|
29 |
|
30 |
|
31 | const slowConnection = typeof window !== 'undefined' &&
|
32 | navigator['connection'] &&
|
33 | ['slow-2g', '2g'].indexOf(navigator['connection'].effectiveType) !== -1;
|
34 |
|
35 | const defaultConfig = {
|
36 |
|
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 |
|
55 | let eventsBinded = false;
|
56 | if (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 |
|
68 | eventsBinded = true;
|
69 | }
|
70 | export { CONCURRENT_PROMISES, CONCURRENT_PROMISES_TS, FOCUS_REVALIDATORS, CACHE_REVALIDATORS, MUTATION_TS, cache };
|
71 | export default defaultConfig;
|