all files / src/util/ reducer.js

87.5% Statements 21/24
81.82% Branches 9/11
100% Functions 2/2
86.96% Lines 20/23
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                                  215× 215×   12×     202× 120× 82× 82×     76×                          
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict";
/**
 * Creates an reducer that works on an object where you can create, delete and update properties of type Object.
 * The key of properties always matches the id property of the value object.
 *
 * @param actionNames
 * Object with: create, update, delete action names
 * @param elementReducer
 * A reducer for a single object that supports the actionNames.create and actionNames.update action.
 * @param initialState (optional)
 * @param idProperty
 * The name of the property to fetch the id from the action. Default: 'id'
 * @returns {crudReducer}
 */
function genCrudReducer(actionNames, elementReducer, idProperty) {
    Eif (idProperty === void 0) { idProperty = 'id'; }
    console.assert(actionNames.length === 2, "ActionNames must contain 2 names for create, delete in that order");
    var CREATE_ACTION = actionNames[0], DELETE_ACTION = actionNames[1];
    return function crudReducer(state, action) {
        var id = action[idProperty];
        switch (action.type) {
            case CREATE_ACTION:
                return Object.assign({}, state, (_a = {}, _a[id] = elementReducer(undefined, action), _a));
            case DELETE_ACTION:
                var newState = Object.assign({}, state);
                delete newState[id];
                return newState;
            default:
                if (id === undefined)
                    return state;
                var elementState = state[id];
                if (elementState == undefined) {
                    // Do not update what we don't have.
                    // TODO: Log warning, or document why not.
                    return state;
                }
                var updatedElement = elementReducer(elementState, action);
                Iif (updatedElement == undefined) {
                    console.error("ElementReducer has some problem: ", elementReducer, " with action: ", action);
                    throw new Error("Reducer must return the original state if they not implement the action. Check action " + action.type + ".");
                }
                return Object.assign({}, state, (_b = {},
                    _b[id] = updatedElement,
                    _b
                ));
        }
        var _a, _b;
    };
}
exports.genCrudReducer = genCrudReducer;