Skip to content

Instantly share code, notes, and snippets.

@geta6
Created December 18, 2015 06:57
Show Gist options
  • Save geta6/f808923f09eccf36feda to your computer and use it in GitHub Desktop.
Save geta6/f808923f09eccf36feda to your computer and use it in GitHub Desktop.

Revisions

  1. geta6 created this gist Dec 18, 2015.
    36 changes: 36 additions & 0 deletions actionGenerator.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,36 @@
    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)});
    }
    12 changes: 12 additions & 0 deletions exampleItemAction.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,12 @@
    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 });
    },
    });