- commit
- b143e9f
- parent
- d0a0d68
- author
- Eric Bower
- date
- 2024-02-23 20:53:12 +0000 UTC
chore: make clearTimers more ergonomic (#42)
2 files changed,
+37,
-5
+20,
-5
1@@ -32,7 +32,11 @@ export function poll(parentTimer: number = 5 * SECONDS, cancelType?: string) {
2 };
3 }
4
5-export const clearTimers = createAction<string[]>("clear-timers");
6+type ClearTimerPayload = string | { type: string; payload: { key: string } };
7+
8+export const clearTimers = createAction<
9+ ClearTimerPayload | ClearTimerPayload[]
10+>("clear-timers");
11
12 /**
13 * timer() will create a cache timer for each `key` inside
14@@ -54,15 +58,26 @@ export function timer(timer: number = 5 * MINUTES) {
15 yield* call(() => op(action));
16 const idA = getIdFromAction(action);
17
18- const matchFn = (act: AnyAction) => {
19+ const matchFn = (
20+ act: ActionWithPayload<ClearTimerPayload | ClearTimerPayload[]>,
21+ ) => {
22 if (act.type !== `${clearTimers}`) return false;
23 if (!act.payload) return false;
24- const ids: string[] = act.payload || [];
25- return ids.some((id) => idA === id || id === "*");
26+ const ids = Array.isArray(act.payload) ? act.payload : [act.payload];
27+ return ids.some((id) => {
28+ if (id === "*") {
29+ return true;
30+ }
31+ if (typeof id === "string") {
32+ return idA === id;
33+ } else {
34+ return idA === getIdFromAction(id);
35+ }
36+ });
37 };
38 yield* race([
39 sleep(timer),
40- take(matchFn) as Operation<void>,
41+ take(matchFn as any) as Operation<void>,
42 ]);
43
44 delete map[action.payload.key];
+17,
-0
1@@ -37,6 +37,23 @@ it(tests, "should let user cancel timer", async () => {
2 expect(called).toBe(2);
3 });
4
5+it(tests, "should let user cancel timer with action obj", async () => {
6+ let called = 0;
7+ await run(function* () {
8+ yield* spawn(function* () {
9+ yield* timer(10_000)("ACTION", function* () {
10+ called += 1;
11+ });
12+ });
13+ const action = { type: "ACTION", payload: { key: "my-key" } };
14+ yield* put(action);
15+ yield* sleep(1);
16+ yield* put(clearTimers(action));
17+ yield* put(action);
18+ });
19+ expect(called).toBe(2);
20+});
21+
22 it(tests, "should let user cancel timer with wildcard", async () => {
23 let called = 0;
24 await run(function* () {