insomnia/app/ui/redux/modules/entities.js

59 lines
1.2 KiB
JavaScript
Raw Normal View History

2016-11-10 05:56:23 +00:00
import * as db from '../../../common/database';
import * as models from '../../../models';
const ENTITY_CHANGES = 'entities/changes';
// ~~~~~~~~ //
// Reducers //
// ~~~~~~~~ //
function getReducerName (type) {
const trailer = type.match(/s$/) ? '' : 's';
return `${type.slice(0, 1).toLowerCase()}${type.slice(1)}${trailer}`;
}
const initialState = {};
2016-11-10 01:15:27 +00:00
for (const type of models.types()) {
initialState[getReducerName(type)] = {};
}
export default function (state = initialState, action) {
switch (action.type) {
case ENTITY_CHANGES:
const newState = Object.assign({}, state);
const {changes} = action;
for (const [event, doc] of changes) {
const referenceName = getReducerName(doc.type);
switch (event) {
case db.CHANGE_INSERT:
case db.CHANGE_UPDATE:
newState[referenceName][doc._id] = doc;
break;
case db.CHANGE_REMOVE:
delete newState[referenceName][doc._id];
break;
default:
break;
}
}
return newState;
default:
return state;
}
}
// ~~~~~~~ //
// Actions //
// ~~~~~~~ //
export function addChanges (changes) {
return {type: ENTITY_CHANGES, changes};
}