Skip to content

Instantly share code, notes, and snippets.

@kaisermann
Last active July 6, 2017 15:15
Show Gist options
  • Save kaisermann/11d0bc926f153e84ebe6935ed1b84084 to your computer and use it in GitHub Desktop.
Save kaisermann/11d0bc926f153e84ebe6935ed1b84084 to your computer and use it in GitHub Desktop.
Redux routine creator utility - async action types and action creators
/* Generates an action creator FSA compliant
* Based on 'redux-actions' createAction method
* https://github.com/acdlite/redux-actions/blob/master/src/createAction.js
*/
export default function createAction (type, payloadTransform, metaTransform) {
return (...args) => {
const action = { type }
const payload =
args[0] instanceof Error || typeof payloadTransform !== 'function'
? args[0]
: payloadTransform(...args)
if (payload instanceof Error) action.error = true
if (payload !== undefined) action.payload = payload
if (typeof metaTransform === 'function') {
action.meta = metaTransform(...args)
}
return action
}
}
import createAction from './createAction'
/*
* Utility to create async routine action creators and action types
* Creates a ${prefix}_TRIGGER, ${prefix}_REQUEST, ${prefix}_SUCCESS,
* ${prefix}_FAILURE, ${prefix}_FULLFILL
*
* Returns an object containing the action types and creators
*/
const suffixes = ['TRIGGER', 'REQUEST', 'SUCCESS', 'FAILURE', 'FULLFILL']
export default function createRoutine (
prefix = '',
payloadTransform,
metaTransform
) {
prefix = prefix.toUpperCase()
return suffixes.reduce((acc, suffix) => {
const type = `${prefix}_${suffix}`
// Uppercase properties should denote the action type
acc[suffix] = type
// Lowercase properties should denote the action creators
acc[suffix.toLowerCase()] = createAction(
type,
payloadTransform,
metaTransform
)
return acc
}, {})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment