Created
December 18, 2015 06:57
-
-
Save geta6/f808923f09eccf36feda 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 get from 'lodash/object/get'; | |
import isError from 'lodash/lang/isError'; | |
import keyMirror from 'fbjs/lib/keyMirror'; | |
export function actionGenerator(displayName, actions) { | |
if (process.env.NODE_ENV === 'development') { | |
Object.keys(actions).forEach(actionName => { | |
if (actions[actionName]) { | |
console.assert(/regeneratorRuntime\.async/.test(actions[actionName].toString()), `${displayName}.${actionName} should be async function`); | |
} | |
}); | |
} | |
return Object.assign((context, payload) => { | |
return new Promise(async (resolve, reject) => { | |
const actionType = get(payload, ['type']); | |
try { | |
const action = actions[actionType]; | |
if (!action) { | |
reject(new Error(`No action responded to ${displayName}.`)); | |
} else { | |
console.info(`execute ${displayName}.${actionType}`); | |
resolve(await action({context, payload})); | |
} | |
} catch (error) { | |
if (isError(error)) { | |
// Normal Error | |
reject(Object.assign(error, {message: `${error.message} (${displayName}.${actionType})`})); | |
} else { | |
// Network Error | |
const message = `${error.status} ${error.statusText}`; | |
reject(new Error(message)); | |
} | |
} | |
}); | |
}, {displayName, actionTypes: keyMirror(actions)}); | |
} |
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 get from 'lodash/object/get'; | |
import axios from 'axios'; | |
import ItemStore from '../stores/ItemStore'; | |
export default actionGenerator('ItemAction', { | |
async fetchItem({ context, payload }) { | |
const id = get(payload, ['entity', 'item', 'id']); | |
const res = await axios.get(`/api/items/${id}.json`); | |
const item = get(res, ['data', 'data']); | |
context.dispatch(ItemStore.dispatchTypes.SET_ITEM, { item }); | |
}, | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment