Last active
May 18, 2016 00:34
-
-
Save orther/bbb0642f2ea068a9dc13db64383318f2 to your computer and use it in GitHub Desktop.
Mikko's example redux API middleware using whatwg-fetch
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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({ promise, types, ...rest }, next) { | |
const [ REQUEST, SUCCESS, FAILURE ] = types; | |
// Dispatch your request action so UI can showing loading indicator | |
next({ ...rest, type: REQUEST }); | |
const api = (url, params = {}) => { | |
// fetch by default doesn't include the same-origin header. Add this by default. | |
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(url, params) | |
.then(checkStatus) | |
.then(parseJSON) | |
.then(data => { | |
// Dispatch your success action | |
next({ ...rest, payload: data, type: SUCCESS }); | |
}) | |
.catch(error => { | |
// Dispatch your failure action | |
next({ ...rest, error, type: FAILURE }); | |
}); | |
}; | |
return promise(api); | |
} | |
export function createApiMiddleware() { | |
return function() { | |
return next => action => isRequest(action) ? makeRequest(action, next) : next(action); | |
}; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export function fetchCuratedList(id) { | |
return { | |
types: [ | |
Constants.CURATED_LIST_FETCH_REQUESTED, | |
Constants.CURATED_LIST_RECEIVE, | |
Constants.CURATED_LIST_FETCH_FAILED | |
], | |
promise: api => api('/api/curatedlist/' + id) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment