Skip to content

Commit

Permalink
chore: make clearTimers more ergonomic (#42)
Browse files Browse the repository at this point in the history
  • Loading branch information
neurosnap authored Feb 23, 2024
1 parent d0a0d68 commit b143e9f
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 5 deletions.
25 changes: 20 additions & 5 deletions supervisor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,11 @@ export function poll(parentTimer: number = 5 * SECONDS, cancelType?: string) {
};
}

export const clearTimers = createAction<string[]>("clear-timers");
type ClearTimerPayload = string | { type: string; payload: { key: string } };

export const clearTimers = createAction<
ClearTimerPayload | ClearTimerPayload[]
>("clear-timers");

/**
* timer() will create a cache timer for each `key` inside
Expand All @@ -54,15 +58,26 @@ export function timer(timer: number = 5 * MINUTES) {
yield* call(() => op(action));
const idA = getIdFromAction(action);

const matchFn = (act: AnyAction) => {
const matchFn = (
act: ActionWithPayload<ClearTimerPayload | ClearTimerPayload[]>,
) => {
if (act.type !== `${clearTimers}`) return false;
if (!act.payload) return false;
const ids: string[] = act.payload || [];
return ids.some((id) => idA === id || id === "*");
const ids = Array.isArray(act.payload) ? act.payload : [act.payload];
return ids.some((id) => {
if (id === "*") {
return true;
}
if (typeof id === "string") {
return idA === id;
} else {
return idA === getIdFromAction(id);
}
});
};
yield* race([
sleep(timer),
take(matchFn) as Operation<void>,
take(matchFn as any) as Operation<void>,
]);

delete map[action.payload.key];
Expand Down
17 changes: 17 additions & 0 deletions test/timer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,23 @@ it(tests, "should let user cancel timer", async () => {
expect(called).toBe(2);
});

it(tests, "should let user cancel timer with action obj", async () => {
let called = 0;
await run(function* () {
yield* spawn(function* () {
yield* timer(10_000)("ACTION", function* () {
called += 1;
});
});
const action = { type: "ACTION", payload: { key: "my-key" } };
yield* put(action);
yield* sleep(1);
yield* put(clearTimers(action));
yield* put(action);
});
expect(called).toBe(2);
});

it(tests, "should let user cancel timer with wildcard", async () => {
let called = 0;
await run(function* () {
Expand Down

0 comments on commit b143e9f

Please sign in to comment.