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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344 | 7x
7x
7x
7x
5x
7x
7x
35x
7x
7x
35x
11x
24x
7x
60x
47x
33x
31x
7x
7x
7x
7x
7x
7x
7x
60x
7x
7x
7x
7x
7x
7x
7x
23x
22x
1x
7x
11x
1x
10x
7x
7x
35x
35x
24x
9x
24x
35x
7x
35x
35x
21x
271x
31x
4x
236x
7x
39x
39x
39x
39x
2x
2x
39x
100x
25x
25x
39x
31x
31x
31x
31x
31x
19x
8x
12x
12x
2x
2x
2x
4x
4x
4x
4x
4x
8x
2x
1x
2x
2x
2x
2x
2x
39x
29x
25x
4x
39x
1x
38x
1x
37x
14x
29x
29x
29x
108x
29x
29x
25x
25x
29x
39x
1x
38x
1x
37x
35x
13x
13x
8x
5x
3x
| // @flow
import get from 'lodash/get'
import isObject from 'lodash/isObject'
if (typeof (fetch) === 'undefined') {
require('isomorphic-fetch')
}
// Generic fetch type
const GFT = '__FETCH__'
// ID that gets incremented for each fetch
let FETCH_ID = 0
// Get's the next fetch ID, which can be passed in to `fetch`, and allows for
// tracking the fetch or aborting it.
export const getID = () => ++FETCH_ID
// Active fetches, can still be aborted
const activeFetches = {
[GFT]: []
}
// Remove a fetch from the active pool
const removeFetch = (sig) => {
if (sig.type === GFT) {
activeFetches[GFT].splice(activeFetches[GFT].indexOf(sig.id), 1)
} else {
delete activeFetches[sig.type]
}
}
// Check if a fetch is still active
export const isActive = (sig) => {
if (sig.type === GFT) return activeFetches[GFT].includes(sig.id)
if (activeFetches[sig.type] === undefined) return false
if (sig.id === undefined) return true
return activeFetches[sig.type] === sig.id
}
// Action types
export const ABORTED_FETCH = 'aborted fetch'
export const ABORT_FETCH_FAILED = 'abort fetch failed'
export const INCREMENT_FETCH = 'increment outstanding fetches'
export const DECREMENT_FETCH = 'decrement outstanding fetches'
export const FETCH = 'fetch'
export const FETCH_MULTIPLE = 'fetch multiple'
export const FETCH_ERROR = 'fetch error'
// Simple action creator
const createAction = (type) => (payload) => ({type, payload})
// Main actions to be dispatched
export const fetchAction = createAction(FETCH)
export const fetchMultiple = createAction(FETCH_MULTIPLE)
export default fetchAction
// Internally dispatched actions
const abortedFetch = createAction(ABORTED_FETCH)
const abortFetchFailed = createAction(ABORT_FETCH_FAILED)
const fetchError = createAction(FETCH_ERROR)
/**
* Call decrement and dispatch "aborted" and "decrement" actions. If `id` is
* not set, cancel all fetches for the given type.
*/
export const abortFetch = (sig) => {
if (isActive(sig)) {
return [
abortedFetch(sig),
decrementFetches(sig)
]
} else {
return abortFetchFailed(sig)
}
}
// Abort all active fetches
export const abortAllFetches = () =>
Object.keys(activeFetches).reduce((aborts, fetchType) => {
if (fetchType === GFT) {
return [
...aborts,
...activeFetches[GFT].map(id => abortFetch({type: GFT, id}))
]
} else {
return [
...aborts,
abortFetch({type: fetchType, id: activeFetches[fetchType]})
]
}
}, [])
/**
* Send an increment action and add the fetch to the active list. This will also
* abort a previous fetch of the same type if it exists.
*/
const incrementFetches = (payload) => {
const actions = [{
type: INCREMENT_FETCH,
payload
}]
if (payload.type === GFT) activeFetches[GFT].push(payload.id)
else {
if (activeFetches[payload.type] !== undefined) {
actions.push(abortFetch({
type: payload.type,
id: activeFetches[payload.type]
}))
}
activeFetches[payload.type] = payload.id
}
return actions
}
/**
* Send a decrement action and remove the fetch from the active list.
*/
const decrementFetches = (signature) => {
removeFetch(signature)
return {
type: DECREMENT_FETCH,
payload: signature
}
}
// Redux middleware
export const middleware = (store) => (next) => (action) => {
switch (get(action, 'type')) {
case FETCH:
return store.dispatch(runFetchAction(action.payload, store.getState()))
case FETCH_MULTIPLE:
return store.dispatch(runFetchMultiple(action.payload, store.getState()))
default:
return next(action)
}
}
/**
* Calls fetch, adds Auth and Content header if needed. Automatically parses
* content based on type.
*
* @returns Promise
*/
function runFetch ({
signature,
options = {},
retry = false,
url
}, state) {
const headers = {
...createAuthorizationHeader(state),
...createContentHeader(options.body),
...(options.headers || {})
}
const filteredHeaders = {}
// Allow removing generated headers by specifiying { header: null } in
// options.headers. Do this in two steps because otherwise we're modifying
// the object as we're iterating over it.
Object.keys(headers)
.filter(key => headers[key] !== null && headers[key] !== undefined)
.forEach(key => { filteredHeaders[key] = headers[key] })
return fetch(url, {
...options,
body: serialize(options.body),
headers: filteredHeaders
})
.then(checkStatus)
.then(createResponse)
.then(async (response) =>
(retry && isActive(signature) && await retry(response))E
? runFetch({signature, options, retry, url}, state)
: response)
}
/**
* Part of Redux action cycle. Returns an array of actions.
*/
function runFetchAction ({
type = GFT,
id = getID(),
next,
options = {},
retry = false,
url
}, state) {
// Fetch signature based on the `type` and `id`
const signature = {type, id}
// If next does not exist or only takes a response, dispatch on error
const dispatchFetchError = !next || next.length < 2
// Wrap next so that we can parse the response
const wrappedNext = wrapNext(next)
return [
incrementFetches({type, id, options, url}),
runFetch({signature, options, retry, url}, state)
.then((response) => {
if (isActive(signature)) {
return [
decrementFetches(signature),
wrappedNext(null, response)
]
}
})
.catch((error) => {
return createErrorResponse(error)
.then((response) => {
if (isActive(signature)) {
const actions = [
decrementFetches(signature),
wrappedNext(error, response)
]
if (dispatchFetchError) actions.push(fetchError(response))
return actions
}
})
})
]
}
/**
* @returns Array of actions
*/
function runFetchMultiple ({
type = GFT,
id = getID(), // One ID for all fetch IDs in a fetch multiple
fetches,
next
}, state) {
const signature = {type, id}
const dispatchFetchError = !next || next.length < 2
const wrappedNext = wrapNext(next)
return [
incrementFetches({type, id, fetches}),
Promise.all(fetches.map((fetch) => runFetch({...fetch, signature}, state)))
.then((responses) => {
if (isActive(signature)) {
return [
decrementFetches(signature),
wrappedNext(null, responses)
]
}
})
.catch((error) =>
createErrorResponse(error)
.then((response) => {
E if (isActive(signature)) {
const actions = [
decrementFetches(signature),
wrappedNext(error, response)
]
if (dispatchFetchError) actions.push(fetchError(response))
return actions
}
}))
]
}
/**
* TODO: Expose this function to allow for customization.
*/
function createAuthorizationHeader (state) {
return state.user && state.user.idToken
? {Authorization: `bearer ${state.user.idToken}`}
: {}
}
function checkStatus (res) {
if (res.status >= 200 && res.status < 300) {
return res
} else {
throw res
}
}
function createContentHeader (body) {
if (body instanceof window.FormData) {
return {}
} else if (isObject(body)) {
return {
'Accept': 'application/json',
'Content-Type': 'application/json;charset=UTF-8'
}
} else {
return {}
}
}
function createErrorResponse (res) {
return res.headers
? createResponse(res)
: Promise.resolve(res)
}
function createResponse (res) {
return deserialize(res)
.then((value) => {
res.value = value
return res
})
.catch((err) => {
res.value = err
return res
})
}
async function deserialize (res) {
const header =
`${res.headers.get('Content-Type')} ${res.headers.get('Content')}`
if (header.indexOf('json') > -1) return res.json()E
if (header.indexOf('octet-stream') > -1) return res.arrayBuffer()
if (header.indexOf('text') > -1) return res.text()
}
function serialize (body) {
if (body instanceof window.FormData) {
return body
} else if (isObject(body)) {
return JSON.stringify(body)
} else {
return body
}
}
function wrapNext (next) {
return function (error, response) {
Eif (next) {
if (next.length > 1) {
return next(error, response)
} else if (!error) {
return next(response)
}
}
}
}
|