-
Notifications
You must be signed in to change notification settings - Fork 346
Expand file tree
/
Copy pathuseHandler.ts
More file actions
82 lines (71 loc) · 2.41 KB
/
useHandler.ts
File metadata and controls
82 lines (71 loc) · 2.41 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
79
80
81
82
import React from 'react';
import { useGetActionInput, useConcurrencyConfig } from '../configuration';
import type { ActionHandler } from '../actions';
import type { Task } from '../tasks';
import { useProcessTasks } from '../tasks';
import type {
HandleTaskInput,
HandleTasksInput,
HandleTasksState,
HandleTaskState,
InferTask,
UseHandlerOptions,
UseHandlerOptionsWithItems,
} from './types';
const isOptionsWithItems = <T extends Task>(
options?: UseHandlerOptions<T> | UseHandlerOptionsWithItems<T>
): options is UseHandlerOptionsWithItems<T> =>
!!(options as UseHandlerOptionsWithItems<T>)?.items;
const isHandleTaskInput = <T>(
value?: HandleTasksInput | HandleTaskInput<T>
): value is HandleTaskInput<T> => !!(value as HandleTaskInput<T>)?.data;
export function useHandler<
THandler extends ActionHandler,
TTask extends InferTask<THandler>,
>(
handler: THandler,
options: UseHandlerOptionsWithItems<TTask>
): HandleTasksState<TTask>;
export function useHandler<
THandler extends ActionHandler,
TTask extends InferTask<THandler>,
>(
handler: THandler,
options?: UseHandlerOptions<TTask>
): HandleTaskState<TTask>;
export function useHandler<
THandler extends ActionHandler,
TTask extends InferTask<THandler>,
>(
handler: THandler,
options?: UseHandlerOptionsWithItems<TTask> | UseHandlerOptions<TTask>
): HandleTasksState<TTask> | HandleTaskState<TTask> {
const [state, handleProcessing] = useProcessTasks(handler, options);
const getConfig = useGetActionInput();
const { concurrency } = useConcurrencyConfig();
const { reset, isProcessing, tasks, ...rest } = state;
const handleDispatch = React.useCallback(
(input?: HandleTasksInput | HandleTaskInput<TTask['data']>): void => {
const config = getConfig(input?.location);
const hasData = isHandleTaskInput(input);
// clean up previous state for atomic handler
if (hasData) reset();
handleProcessing({
config,
...(hasData
? { data: input.data, all: [input.data] }
: // if no `data` provided, provide `concurrency` to `options`
{
options: {
concurrency,
},
}),
});
},
[getConfig, handleProcessing, reset, concurrency]
);
if (isOptionsWithItems(options)) {
return [{ ...rest, isProcessing, reset, tasks }, handleDispatch];
}
return [{ isProcessing, task: tasks?.[0] }, handleDispatch];
}