-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcreateLoader.ts
79 lines (70 loc) · 1.98 KB
/
createLoader.ts
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
79
/* eslint-disable react-hooks/rules-of-hooks */
import { Operation, sleep, spawn, call, useAbortSignal } from "effection";
import { CreateSpinnerOptions, createSpinner } from "./createSpinner";
import { update } from "./UpdateContext";
import { LoaderFn } from "../hooks/useLoader";
export type CreateLoaderOptions<T> = {
load: LoaderFn<T>;
showSpinnerAfterInterval: number;
retryAttempts: number;
failedAttemptErrorInterval: number;
retryingMessageInterval: number;
} & CreateSpinnerOptions;
export function createLoader<T>({
load,
retryAttempts,
showSpinnerAfterInterval,
loadingInterval,
loadingSlowlyInterval,
failedAttemptErrorInterval,
retryingMessageInterval,
}: CreateLoaderOptions<T>): () => Operation<void> {
return function* loader() {
yield* update({
type: "started",
});
for (let attempt = 0; attempt <= retryAttempts; attempt++) {
const spinner = yield* spawn(function* () {
if (attempt === 0) {
yield* sleep(showSpinnerAfterInterval);
}
yield* createSpinner({
loadingInterval,
loadingSlowlyInterval,
})();
});
const signal = yield* useAbortSignal();
try {
const result = yield* call(() => load({ attempt, signal }));
yield* update({
type: "success",
value: result,
});
break;
} catch (e) {
yield* spinner.halt();
const error = e instanceof Error ? e : new Error(`${e}`);
if (attempt === retryAttempts) {
yield* update({
type: "failed",
error,
});
} else {
yield* update({
type: "failed-attempt",
attempt,
error,
});
yield* sleep(failedAttemptErrorInterval);
yield* update({
type: "retrying",
error,
});
yield* sleep(retryingMessageInterval);
}
} finally {
yield* spinner.halt();
}
}
};
}