Skip to content

Instantly share code, notes, and snippets.

@ianstormtaylor
Created January 27, 2016 19:25
Show Gist options
  • Save ianstormtaylor/84f3529e218d381a54cc to your computer and use it in GitHub Desktop.
Save ianstormtaylor/84f3529e218d381a54cc to your computer and use it in GitHub Desktop.
import { call, cps, fork, take, put } from 'redux-saga'
/**
* Create a saga.
*
* @param {Object} opts
* @return {Generator}
*/
export function createSaga(opts) {
return function* (getState) {
for (var key in opts) {
var gen = wrapFork(key, opts[key])
yield fork(gen, getState)
}
}
}
/**
* Wrap a `generator` function to only be invoked on actions of `type`.
*
* @param {String} type
* @param {Generator} generator
*/
function wrapFork(type, generator) {
return function* (getState) {
while (true) {
const action = yield take(type)
const store = { dispatch: put, getState }
yield generator(action, store)
}
}
}
/**
* Wrap a promise-returning `fn` for testability.
*
* @param {Function} fn
* @return {Function}
*/
export function wrap(fn) {
return function (...args) {
return call(fn, ...args)
}
}
/**
* Wrap a thunk-returning `fn` for testability.
*
* @param {Function} fn
* @return {Function}
*/
export function wrapThunk(fn) {
return function (...args) {
return cps(fn, ...args)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment