Skip to content

Commit e98f2ec

Browse files
committed
Refactored the fetchMiddleware into its own file.
1 parent 095013a commit e98f2ec

File tree

2 files changed

+38
-36
lines changed

2 files changed

+38
-36
lines changed

src/redux/configureStore.js

Lines changed: 1 addition & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -1,47 +1,12 @@
11
import thunk from 'redux-thunk';
22
import rootReducer from './modules';
3+
import { fetchMiddleware } from './middleware/FetchMiddleware';
34
import {
45
applyMiddleware,
56
compose,
67
createStore
78
} from 'redux';
89

9-
const fetchMiddleware = store => next => action => {
10-
next(action);
11-
12-
if (action.meta && action.meta.endpoint) {
13-
let options;
14-
switch (action.meta.method) {
15-
case 'POST':
16-
options = {
17-
method: 'post',
18-
headers: {
19-
'Content-Type': 'application/json'
20-
},
21-
body: JSON.stringify(action.meta.body)
22-
};
23-
24-
break;
25-
default:
26-
options = {
27-
method: 'get'
28-
};
29-
}
30-
fetch(action.meta.endpoint, options)
31-
.then(function (response) {
32-
return response.json();
33-
}).then(function (json) {
34-
console.log(json);
35-
if (action.meta.success) {
36-
next(action.meta.success(json, action.payload));
37-
}
38-
}).catch(function (ex) {
39-
console.log('parsing failed', ex);
40-
});
41-
console.log('fetching: ' + action.meta.endpoint);
42-
}
43-
};
44-
4510
export default function configureStore (initialState) {
4611
let createStoreWithMiddleware;
4712

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
const fetchMiddleware = store => next => action => {
2+
next(action);
3+
4+
if (action.meta && action.meta.endpoint) {
5+
let options;
6+
switch (action.meta.method) {
7+
case 'POST':
8+
options = {
9+
method: 'post',
10+
headers: {
11+
'Content-Type': 'application/json'
12+
},
13+
body: JSON.stringify(action.meta.body)
14+
};
15+
16+
break;
17+
default:
18+
options = {
19+
method: 'get'
20+
};
21+
}
22+
fetch(action.meta.endpoint, options)
23+
.then(function (response) {
24+
return response.json();
25+
}).then(function (json) {
26+
console.log(json);
27+
if (action.meta.success) {
28+
next(action.meta.success(json, action.payload));
29+
}
30+
}).catch(function (ex) {
31+
console.log('parsing failed', ex);
32+
});
33+
console.log('fetching: ' + action.meta.endpoint);
34+
}
35+
};
36+
37+
export { fetchMiddleware as fetchMiddleware };

0 commit comments

Comments
 (0)