-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrequest.js
68 lines (61 loc) · 1.6 KB
/
request.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
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
import { call, cancelled as cancelledSaga, put } from 'redux-saga/effects'
/**
* request can be used to call a promise in a saga and have events
* dispatched indicating the promises status.
*/
// Creates types and action creators for a request.
export function createRequest(type) {
const BASE = type
const STARTED = `${type}_STARTED`
const SUCCEEDED = `${type}_SUCCEEDED`
const ERRORED = `${type}_ERRORED`
const CANCELLED = `${type}_CANCELLED`
return {
BASE,
STARTED,
SUCCEEDED,
ERRORED,
CANCELLED,
start: meta => ({
type: STARTED,
meta,
}),
success: (payload, meta) => ({
type: SUCCEEDED,
payload,
meta,
}),
error: (error, meta) => ({
type: ERRORED,
meta,
}),
cancel: meta => ({
type: CANCELLED,
meta,
}),
}
}
// Calls a promise. Puts events for start, success, error, and cancelled.
export function* requestSaga(type, func, meta) {
// Get the request event types for this type.
const { start, success, error, cancel } = type
// Put the started type.
yield put(start(meta))
try {
// Attempt to call the promise.
const payload = yield call(...func)
// If it's successful put the succeeded type.
return yield put(success(payload, meta))
} catch (e) {
// If it's unsuccessful put the errored type.
return yield put(error(e, meta))
} finally {
if (yield cancelledSaga()) {
// If this saga is cancelled put the cancelled type.
return yield put(cancel(meta))
}
}
}
export function request(type, func, meta) {
return call(requestSaga, type, func, meta)
}