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 | 7x
7x
7x
7x
63x
10x
32x
2x
2x
1x
2x
10x
10x
8x
2x
10x
1x
9x
1x
8x
2x
10x
10x
10x
10x
6x
6x
6x
10x
1x
9x
1x
8x
9x
9x
9x
5x
4x
3x
| // @flow
import isObject from 'lodash/isObject'
import createAction from 'redux-actions/lib/createAction'
if (typeof (fetch) === 'undefined') {
require('isomorphic-fetch')
}
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'
export const incrementFetches = createAction(INCREMENT_FETCH)
export const decrementFetches = createAction(DECREMENT_FETCH)
export const fetchAction = createAction(FETCH)
export const fetchMultiple = createAction(FETCH_MULTIPLE)
export const fetchError = createAction(FETCH_ERROR)
export function middleware (store) {
return (next) => (action) => {
if (action.type === FETCH) {
return store.dispatch(runFetchAction(action.payload, store.getState()))
} else if (action.type === FETCH_MULTIPLE) {
return store.dispatch(runFetchMultiple(action.payload, store.getState()))
} else {
return next(action)
}
}
}
export default fetchAction
/**
* Calls fetch, adds Auth and Content header if needed. Automatically parses content based on type.
*
* @returns Promise
*/
export function runFetch ({
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 && await retry(response))
? runFetch({options, retry, url}, state)
: response)
}
export function runFetchAction ({
next,
options = {},
retry = false,
url
}, state) {
const dispatchFetchError = !next || next.length < 2
const wrappedNext = wrapNext(next)
return [
incrementFetches({options, url}),
runFetch({options, retry, url}, state)
.then((response) => [decrementFetches({options, url}), wrappedNext(null, response)])
.catch((error) =>
createErrorResponse(error)
.then((response) => {
const actions = [decrementFetches({options, url}), wrappedNext(error, response)]
if (dispatchFetchError) actions.push(fetchError(response))
return actions
}))
]
}
/**
* @returns Promise
*/
export function runFetchMultiple ({
fetches,
next
}, state) {
const dispatchFetchError = !next || next.length < 2
const wrappedNext = wrapNext(next)
E
return [
...fetches.map(({options, url}) => incrementFetches({options, url})),
Promise.all(fetches.map((fetch) => runFetch(fetch, state)))
.then((responses) => [
...fetches.map(({options, url}) => decrementFetches({options, url})),
wrappedNext(null, responses)
])
.catch((error) =>
createErrorResponse(error)
.then((response) => {
const actions = fetches.map(({options, url}) => decrementFetches({options, url}))
if (dispatchFetchError) actions.push(fetchError(response))
return [...actions, wrappedNext(error, response)]
}))
]
}
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) => ({
url: res.url,
status: res.status,
statusText: res.statusText,
headers: res.headers,
value
}))
.catch((err) => ({
value: err
}))
}
function deserialize (res) {
const header = `${res.headers.get('Content-Type')} ${res.headers.get('Content')}`
if (header.indexOf('application/json') > -1) return res.json()
Iif (header.indexOf('application/ld+json') > -1) return res.json()
Iif (header.indexOf('application/octet-stream') > -1) return res.arrayBuffer()
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)
}
}
}
}
|