All files / src createSagas.js

92.86% Statements 13/14
100% Branches 4/4
75% Functions 3/4
92.86% Lines 13/14

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49                                                4x 4x 4x 4x 4x 4x 4x   4x 1x     4x 1x         4x   4x        
import { takeLatest, takeEvery } from 'redux-saga/effects';
 
/**
 * @typedef {Object} SagaObject - Object containing watcher and worker sagas
 * @property {Generator=} watcher - watcher saga
 * @property {Generator=} worker - worker saga
 * @property {('every'| 'latest')=} watchFor - Accepts
 */
 
/**
 * Function to create watcher and worker sagas for redux store
 * @example
 * createSagas({
 *  FETCH_USERS: function* fetchUser(){
 *    const users = yield call(api.fetchUsers);
 *   }
 * })
 * @param {Object<ActionName, Generator|SagaObject>} sagasObject
 * Object containing module's sagas.
 * The key is name of  the action that triggers the saga and value is generator or SagaObject
 * @returns {Generator[]}  array of watcher sagas
 *
 */
function createSagas(sagasObject) {
  const arr = [];
  const delimiter = '__@';
  const sagaKeys = Object.keys(sagasObject);
  sagaKeys.forEach(key => {
    const action = key.split(delimiter)[0];
    const workerSaga = sagasObject[key];
    const mode = key.split(delimiter)[1] || 'latest';
 
    let watcher = function*() {
      yield takeLatest(action, workerSaga);
    };
 
    if (mode === 'every') {
      watcher = function*() {
        yield takeEvery(action, workerSaga);
      };
    }
 
    arr.push(watcher());
  });
  return arr;
}
 
export default createSagas;