This repository has been archived by the owner on Jan 24, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathfetch-action-creator.ts
221 lines (191 loc) · 5.8 KB
/
fetch-action-creator.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
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
import { AnyAction } from 'redux';
import { ThunkAction, ThunkDispatch } from 'redux-thunk';
export interface AbortAction {
type: string;
}
export type ActionMutator<A extends FetchStateAction> = (action: A) => AnyAction;
export interface Actions {
onAbort?: ActionMutator<AbortAction> | Object;
onReject?: ActionMutator<RejectAction> | Object;
onRequest?: ActionMutator<RequestAction> | Object;
onResolve?: ActionMutator<ResolveAction> | Object;
}
interface Conditional {
(state?: Object): boolean;
}
type FetchAction = ThunkAction<Promise<void>, any, void, AnyAction>;
export interface FetchActionCreator {
default?: FetchActionCreator;
(
id: string,
input: Request | string,
init: Init,
actions: Actions,
conditional?: Conditional
): FetchAction;
}
type FetchStateAction = AbortAction | RejectAction | RequestAction | ResolveAction;
type Init = RequestInit | ((state?: Object) => RequestInit);
export interface RejectAction {
error: Object | string;
headers: Headers | null,
statusCode: null | number;
type: string;
}
export interface RequestAction {
abortController: AbortController | null;
type: string;
}
export interface ResolveAction {
body: Object | string;
headers: Headers;
statusCode: number;
type: string;
}
class FetchError {
headers: Headers;
message: Object | string;
statusCode: number;
constructor(message: Object | string, headers: Headers, statusCode: number) {
this.headers = headers;
this.message = message;
this.statusCode = statusCode;
}
}
const MIN_ERROR_STATUS_CODE: number = 400;
const MAX_ERROR_STATUS_CODE: number = 600;
const createAction = (action: FetchStateAction, actionMutator?: ActionMutator<FetchStateAction> | null | Object): AnyAction => {
if (!actionMutator) {
return action;
}
if (typeof actionMutator === 'object') {
return {
...action,
...actionMutator
};
}
return actionMutator(action);
};
const parseResponse = (response: Response): Promise<[ Object | string, Headers, number ]> => {
const includeMeta = <T = Object | string>(result: T): [ T, Headers, number ] => [ result, response.headers, response.status ];
const response2 = response.clone();
try {
return response2.json().then(includeMeta)
.catch(() => {
return response.text().then(includeMeta);
})
.catch(() => {
return includeMeta('');
});
} catch (e) {
return response.text().then(includeMeta)
.catch(() => {
return includeMeta('');
});
}
};
const fetchActionCreator: FetchActionCreator = (
id: string,
url: Request | string,
init: Init | null = Object.create(null),
actions: Actions | null = Object.create(null),
conditional?: Conditional
): FetchAction =>
(dispatch: ThunkDispatch<any, void, AnyAction>, getState: () => Object): Promise<void> => {
// If we have a condition for fetching, check if we should continue.
if (
typeof conditional === 'function' &&
!conditional(getState())
) {
return Promise.resolve();
}
// Implement AbortController, where possible.
let abortController: AbortController | null = null;
let signal: AbortSignal | null = null;
// If this browser supports AbortController, create one.
if (typeof AbortController !== 'undefined') {
abortController = new AbortController();
signal = abortController.signal;
// When the signal aborts, dispatch the abort action.
signal.addEventListener('abort', () => {
const abortAction: AbortAction = {
type: 'ABORT_' + id
};
dispatch(createAction(
abortAction,
actions !== null &&
Object.prototype.hasOwnProperty.call(actions, 'onAbort') ?
actions.onAbort :
null
));
});
}
// Dispatch the request action.
const requestAction: RequestAction = {
abortController,
type: 'REQUEST_' + id
};
dispatch(createAction(
requestAction,
actions !== null &&
Object.prototype.hasOwnProperty.call(actions, 'onRequest') ?
actions.onRequest :
null
));
// Fetch
const requestInit: null | RequestInit =
typeof init === 'function' ?
init.length ?
init(getState()) :
init() :
init;
return fetch(url, { signal, ...requestInit })
.then(parseResponse)
.then(([ body, headers, statusCode ]: [ Object | string, Headers, number ]) => {
// Check for an error status code.
if (
statusCode >= MIN_ERROR_STATUS_CODE &&
statusCode < MAX_ERROR_STATUS_CODE
) {
throw new FetchError(body, headers, statusCode);
}
// Dispatch the resolve action.
const resolveAction: ResolveAction = {
body,
headers,
statusCode,
type: 'RESOLVE_' + id
};
dispatch(createAction(
resolveAction,
actions !== null &&
Object.prototype.hasOwnProperty.call(actions, 'onResolve') ?
actions.onResolve :
null
));
})
// Dispatch the reject action.
.catch((err: Error | FetchError) => {
const rejectAction: RejectAction = {
error: err.message || 'Script error',
headers:
err instanceof FetchError ?
err.headers :
null,
statusCode:
err instanceof FetchError ?
err.statusCode :
null,
type: 'REJECT_' + id
};
dispatch(createAction(
rejectAction,
actions !== null &&
Object.prototype.hasOwnProperty.call(actions, 'onReject') ?
actions.onReject :
null
));
});
};
fetchActionCreator.default = fetchActionCreator;
module.exports = fetchActionCreator;