/
safeEffect.ts
59 lines (51 loc) · 1.51 KB
/
safeEffect.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
import { Action } from 'redux';
import {
call,
put,
takeLatest,
spawn,
} from 'redux-saga/effects';
import { errorSlice } from '../state/errorSlice';
import { loadingSlice } from '../state/loadingSlice';
import { createCommand } from './createCommand';
import { commandName } from '../types';
const { actions: {setError, clearError} } = errorSlice;
const { actions: {setLoading, unsetLoading} } = loadingSlice;
function safeSagaWrapper(saga: (action: any) => Generator<any>) {
return function* (action: Action) {
const commandName: commandName = action.type;
yield put(setLoading(commandName));
yield put(clearError(commandName));
try {
yield saga(action);
// yield showSuccessSnackBar(sagaName);
} catch (error) {
yield call(console.warn, error);
const errorCasted = error as Error;
yield put(
setError({
commandName,
error: error,
message: errorCasted?.message,
thrown: new Date(),
}),
);
// yield showFailureSnackBar(commandName);
} finally {
yield put(unsetLoading(commandName));
}
};
}
export function* takeLatestSafe(
actionType: string,
saga: (action: any) => Generator<any>,
) {
function* takeSafeSaga() {
const wrappedSaga = safeSagaWrapper(saga);
yield takeLatest(actionType, wrappedSaga);
}
yield spawn(takeSafeSaga);
}
export function* takeLatestCommandSafe(command: ReturnType<typeof createCommand>) {
yield takeLatestSafe(command.action.type, command.saga);
}