All files index.js

100% Statements 30/30
100% Branches 6/6
100% Functions 12/12
100% Lines 29/29
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 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71                  3x     1x     4x             1x 9x 4x   5x 5x           1x 1x 5x 5x 5x 7x 12x 12x 3x           2x           5x 5x 10x 10x 10x 20x 20x 5x     5x 5x         5x  
// @flow
 
import invariant from 'invariant'
 
export type Transport = {
    send: (state: any, action: Object) => ?Promise<any>
}
 
export function backendAction() {
    return (state: any) => state;
}
 
const APPLY_ACTION_TYPE = 'APPLY_STATE_ACTION';
 
export function applyAction(state: any) {
    return {
        type: APPLY_ACTION_TYPE,
        payload: state
    }
}
 
export function busMiddleware(transport: Transport): Function {
    return function (store: any, promise: Promise<any>, action: any) {
        if (action.type === APPLY_ACTION_TYPE) {
            return action.payload
        }
        return promise.then(state => {
            return transport.send(state, action) || state;
        })
    }
}
 
export function backendMiddleware(reducers: Object): Function {
    invariant(typeof reducers === 'object', 'reducers must be an object');
    return function (store: any, promise: Promise<any>, action: any) {
        return Promise.resolve(promise).then(state => {
            const actions = makeActions(reducers, state);
            for (let i in actions) {
                for (let j in actions[i]) {
                    const handler = actions[i][j];
                    if (action.type === j) {
                        return handler(
                            ...action.payload
                        )
                    }
                }
            }
            return state
        })
    }
}
 
function makeActions(reducers: Object, state: any) {
    const actions = {};
    for (let i in reducers) {
        actions[i] = {};
        invariant(typeof reducers[i] === 'object', 'reducer must be an object');
        for (let j in reducers[i]) {
            invariant(typeof reducers[i][j] === 'function', 'action must be a function');
            actions[i][j] = (...args) => {
                return Promise.resolve(
                    reducers[i][j](state[i], ...args, actions)
                ).then(result => {
                    state[i] = result;
                    return state
                })
            }
        }
    }
    return actions
}