Last active
May 23, 2016 17:00
-
-
Save vinzdef/09274552ddf253bf6b45a3d29b97211a to your computer and use it in GitHub Desktop.
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 fetch from 'isomorphic-fetch' | |
| export function retrieve(url, actionCreator, id = null, collection = null) { | |
| return (dispatch, getState) => { | |
| function done(data) { | |
| dispatch(actionCreator(data)) | |
| } | |
| if (id !== null) { | |
| // Grab single from store | |
| if (collection !== null) { | |
| let c = getState()[collection] | |
| const matches = c.filter(i => i.id == id) | |
| if (matches && matches[0]) { | |
| done(matches[0]) | |
| return | |
| } | |
| } | |
| // Fetch single from api | |
| fetch(`${url}/${id}`). | |
| .then(r => r.json()) | |
| .then(data => done(data)) | |
| } else { | |
| // Fetch whole collection from api | |
| fetch(url). | |
| .then(r => r.json()) | |
| .then(data => done(data)) | |
| } | |
| } | |
| } | |
| export function update(url, actionCreator, model) { | |
| return (dispatch) { | |
| fetch(`${url}/${id}`, { | |
| method: 'PATCH', | |
| body: JSON.stringify(model) | |
| }) | |
| .then(r => r.json()) | |
| .then(data => dispatch(actionCreator(data))) | |
| } | |
| } | |
| export function create(url, actionCreator, model) { | |
| return (dispatch) { | |
| fetch(url, { | |
| method: 'POST', | |
| body: JSON.stringify(model) | |
| }) | |
| .then(r => r.json()) | |
| .then(data => dispatch(actionCreator(data))) | |
| } | |
| } | |
| export function remove(url, actionCreator) { | |
| return (dispatch) { | |
| fetch(id, { | |
| method: 'DELETE', | |
| }) | |
| .then(r => r.json()) | |
| .then(data => dispatch(actionCreator(data))) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment