(config = {})
| 8 | }; |
| 9 | |
| 10 | export function install(config = {}) { |
| 11 | const loopConfig = Object.assign({}, defaultLoopConfig, config); |
| 12 | |
| 13 | return (next) => (reducer, initialState, enhancer) => { |
| 14 | const [initialModel, initialCmd] = liftState(initialState); |
| 15 | let cmdsQueue = []; |
| 16 | |
| 17 | const liftReducer = (reducer) => (state, action) => { |
| 18 | const result = reducer(state, action); |
| 19 | const [model, cmd] = liftState(result); |
| 20 | cmdsQueue.push({ originalAction: action, cmd }); |
| 21 | return model; |
| 22 | }; |
| 23 | |
| 24 | const store = next(liftReducer(reducer), initialModel, enhancer); |
| 25 | |
| 26 | function runCmds(queue) { |
| 27 | const promises = queue.map(runCmd).filter((x) => x); |
| 28 | if (promises.length === 0) { |
| 29 | return Promise.resolve(); |
| 30 | } else if (promises.length === 1) { |
| 31 | return promises[0]; |
| 32 | } else { |
| 33 | return Promise.all(promises).then(() => {}); |
| 34 | } |
| 35 | } |
| 36 | |
| 37 | function runCmd({ originalAction, cmd }) { |
| 38 | const cmdPromise = executeCmd(cmd, dispatch, store.getState, loopConfig); |
| 39 | |
| 40 | if (!cmdPromise) { |
| 41 | return null; |
| 42 | } |
| 43 | |
| 44 | return cmdPromise |
| 45 | .then((actions) => { |
| 46 | if (!actions.length) { |
| 47 | return; |
| 48 | } |
| 49 | return Promise.all(actions.map(dispatch)); |
| 50 | }) |
| 51 | .catch((error) => { |
| 52 | console.error(loopPromiseCaughtError(originalAction.type, error)); |
| 53 | throw error; |
| 54 | }); |
| 55 | } |
| 56 | |
| 57 | function dispatch(action) { |
| 58 | if (loopConfig.ENABLE_THUNK_MIGRATION && typeof action === 'function') { |
| 59 | return action(dispatch, store.getState); |
| 60 | } |
| 61 | const result = store.dispatch(action); |
| 62 | const cmdsToRun = cmdsQueue; |
| 63 | cmdsQueue = []; |
| 64 | return runCmds(cmdsToRun).then(() => result); |
| 65 | } |
| 66 | |
| 67 | function replaceReducer(reducer) { |
no test coverage detected