-
Notifications
You must be signed in to change notification settings - Fork 0
/
saga.handleCallbacks.js
42 lines (31 loc) · 1.17 KB
/
saga.handleCallbacks.js
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
import { takeEvery, take, delay, cancel, fork } from 'redux-saga/effects'
const MAX_WAITING_FOR_ACTION = 20000
const INIT_PATTERN = /\/INIT$/
const isInitAction = action => INIT_PATTERN.test(action.type)
const getActionType = (type, target) => type.replace(INIT_PATTERN, `/${target}`)
const getCallback = (payload, name) =>
(payload && payload[name]) || (() => null)
export default function* () {
yield takeEvery(isInitAction, function* ({ type, payload }) {
const onSuccessHandler = getCallback(payload, 'onSuccess')
const onFailureHandler = getCallback(payload, 'onFailure')
let successWatcher
let failureWatcher
function* stopWacthers() {
yield cancel(successWatcher)
yield cancel(failureWatcher)
}
successWatcher = yield fork(function* () {
const action = yield take(getActionType(type, 'SUCCESS'))
onSuccessHandler(action.payload)
yield stopWacthers()
})
failureWatcher = yield fork(function* () {
const action = yield take(getActionType(type, 'FAILURE'))
onFailureHandler(action.payload)
yield stopWacthers()
})
yield delay(MAX_WAITING_FOR_ACTION)
yield stopWacthers()
})
}