. IMO.
, , . , .
, , :
export function fetchData() {
return {
types: [ FETCH_DATA, FETCH_DATA_SUCCESS, FETCH_DATA_FAILURE ],
promise: api => api('foo/bar')
}
}
, types promise . :
import 'whatwg-fetch';
function isRequest({ promise }) {
return promise && typeof promise === 'function';
}
function checkStatus(response) {
if (response.status >= 200 && response.status < 300) {
return response;
} else {
const error = new Error(response.statusText || response.status);
error.response = response.json();
throw error;
}
}
function parseJSON(response) {
return response.json();
}
function makeRequest(urlBase, { promise, types, ...rest }, next) {
const [ REQUEST, SUCCESS, FAILURE ] = types;
next({ ...rest, type: REQUEST });
const api = (url, params = {}) => {
params.credentials = 'same-origin';
params.method = params.method || 'get';
params.headers = params.headers || {};
params.headers['Content-Type'] = 'application/json';
params.headers['Access-Control-Allow-Origin'] = '*';
return fetch(urlBase + url, params)
.then(checkStatus)
.then(parseJSON)
.then(data => {
next({ ...rest, payload: data, type: SUCCESS });
})
.catch(error => {
next({ ...rest, error, type: FAILURE });
});
};
return promise(api);
}
export default function apiMiddleware(urlBase) {
return function() {
return next => action => isRequest(action) ? makeRequest(urlBase, action, next) : next(action);
};
}
, , api. , , . thunk middleware, .