Repository navigation
Expand file tree
/
Copy pathbackground-poll.ts
More file actions
78 lines (68 loc) · 2.36 KB
/
Copy pathbackground-poll.ts
File metadata and controls
78 lines (68 loc) · 2.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import type { ReloadOptions } from '@inertiajs/core';
import { router } from '@inertiajs/react';
let isOutdated = false;
/**
* A deploy leaves this tab on the previous version until it reloads, and the server answers each background reload
* with nothing but a request to reload, so the tab stops asking.
*/
export function stopBackgroundReloads(): void {
isOutdated = true;
}
export function backgroundPollOptions(
requestOptions: ReloadOptions | (() => ReloadOptions),
): () => ReloadOptions {
return () => {
const options =
typeof requestOptions === 'function'
? requestOptions()
: requestOptions;
return {
...options,
onBefore: (visit) =>
isOutdated ? false : options.onBefore?.(visit),
onHttpException: (response) => {
const result = options.onHttpException?.(response);
// Deployment gateways may answer before Laravel can return an Inertia page.
return [502, 503, 504, 520].includes(response.status)
? false
: result;
},
onNetworkError: (error) => {
options.onNetworkError?.(error);
return false;
},
};
};
}
/**
* A background reload that settles once its request does, whether it succeeded, failed or was cancelled, so
* whoever waits on it never starts another one while it is still on its way. Aborting cancels it.
*/
export function reloadInBackground(
options: ReloadOptions,
signal?: AbortSignal,
): Promise<void> {
return new Promise((resolve) => {
if (signal?.aborted || isOutdated) {
resolve();
return;
}
let cancel = () => {};
const onAbort = () => cancel();
signal?.addEventListener('abort', onAbort, { once: true });
router.reload(
backgroundPollOptions({
...options,
onCancelToken: (token) => {
cancel = () => token.cancel();
options.onCancelToken?.(token);
},
onFinish: (visit) => {
signal?.removeEventListener('abort', onAbort);
options.onFinish?.(visit);
resolve();
},
})(),
);
});
}