/* 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;
|