Skip to content

Commit 0ca7dec

Browse files
author
Artur Charaev
committed
export default ready middleware and create middleware as option
1 parent b2b8e6c commit 0ca7dec

File tree

1 file changed

+18
-13
lines changed

1 file changed

+18
-13
lines changed

src/index.js

Lines changed: 18 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -28,12 +28,16 @@ export const actionWith = (actionType, args, payload) => {
2828
if (typeof actionType === 'function') {
2929
nextAction = actionType(...args, payload);
3030
} else {
31-
if (typeof actionType === 'string') {
31+
// convert strings or symbols to FSA object
32+
if (typeof actionType === 'string' || typeof actionType === 'symbol') {
3233
nextAction = { type: actionType };
3334
} else {
3435
nextAction = actionType;
3536
}
36-
nextAction.payload = payload || nextAction.payload;
37+
38+
if (payload) {
39+
nextAction.payload = payload;
40+
}
3741
}
3842
if (payload instanceof Error) {
3943
nextAction.error = true;
@@ -42,45 +46,46 @@ export const actionWith = (actionType, args, payload) => {
4246
return nextAction;
4347
};
4448

45-
const createMiddleware = ({ status = checkStatus, parse = parseResponse }) => (
49+
export const createMiddleware = ({ status = checkStatus, parse = parseResponse }) => (
4650
({ getState }) => next => (action) => {
4751
if (!action[CALL_API]) {
4852
return next(action);
4953
}
5054

51-
let { endpoint, options } = action[CALL_API];
52-
const { types } = action[CALL_API];
55+
const apiAction = action[CALL_API];
5356

5457
// make request endpoint
55-
if (typeof endpoint === 'function') {
56-
endpoint = endpoint(action, getState());
58+
if (typeof apiAction.endpoint === 'function') {
59+
apiAction.endpoint = apiAction.endpoint(action, getState());
5760
}
5861

5962
// make request opts
60-
if (typeof options === 'function') {
61-
options = options(action, getState());
63+
if (typeof apiAction.options === 'function') {
64+
apiAction.options = apiAction.options(action, getState());
6265
}
6366

67+
const { endpoint, options, types } = apiAction;
68+
6469
// action types
6570
const [requestType, successType, failureType] = types;
6671

6772
// dispatch request type
6873
next(actionWith(
69-
requestType, [action, getState()]
74+
requestType, [apiAction, getState()]
7075
));
7176

7277
return fetch(endpoint, options)
7378
.then(status)
7479
.then(parse)
7580
.then(
7681
response => next(actionWith(
77-
successType, [action, getState()], response
82+
successType, [apiAction, getState()], response
7883
)),
7984
error => next(actionWith(
80-
failureType, [action, getState()], error
85+
failureType, [apiAction, getState()], error
8186
))
8287
);
8388
}
8489
);
8590

86-
export default createMiddleware;
91+
export default createMiddleware({});

0 commit comments

Comments
 (0)