2016-11-10 05:56:23 +00:00
|
|
|
import * as db from '../../../common/database';
|
|
|
|
import * as models from '../../../models';
|
2016-09-02 05:45:12 +00:00
|
|
|
|
2016-11-16 17:18:39 +00:00
|
|
|
const ENTITY_CHANGES = 'entities/changes';
|
2016-04-26 07:29:24 +00:00
|
|
|
|
|
|
|
// ~~~~~~~~ //
|
2016-11-16 17:18:39 +00:00
|
|
|
// Reducers //
|
2016-04-26 07:29:24 +00:00
|
|
|
// ~~~~~~~~ //
|
|
|
|
|
2016-09-22 03:32:12 +00:00
|
|
|
function getReducerName (type) {
|
|
|
|
const trailer = type.match(/s$/) ? '' : 's';
|
|
|
|
return `${type.slice(0, 1).toLowerCase()}${type.slice(1)}${trailer}`;
|
2016-04-26 07:29:24 +00:00
|
|
|
}
|
|
|
|
|
2016-11-16 17:18:39 +00:00
|
|
|
const initialState = {};
|
2016-09-22 03:32:12 +00:00
|
|
|
|
2016-11-10 01:15:27 +00:00
|
|
|
for (const type of models.types()) {
|
2016-09-22 03:32:12 +00:00
|
|
|
initialState[getReducerName(type)] = {};
|
2016-08-15 17:04:36 +00:00
|
|
|
}
|
|
|
|
|
2017-03-03 20:09:08 +00:00
|
|
|
export function reducer (state = initialState, action) {
|
2016-09-22 03:32:12 +00:00
|
|
|
switch (action.type) {
|
|
|
|
case ENTITY_CHANGES:
|
2016-11-16 17:18:39 +00:00
|
|
|
const newState = Object.assign({}, state);
|
2016-09-22 03:32:12 +00:00
|
|
|
const {changes} = action;
|
2016-11-16 17:18:39 +00:00
|
|
|
|
2016-09-22 03:32:12 +00:00
|
|
|
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;
|
|
|
|
}
|
|
|
|
}
|
2016-04-26 07:29:24 +00:00
|
|
|
|
|
|
|
// ~~~~~~~ //
|
2016-11-16 17:18:39 +00:00
|
|
|
// Actions //
|
2016-04-26 07:29:24 +00:00
|
|
|
// ~~~~~~~ //
|
|
|
|
|
2016-09-22 03:32:12 +00:00
|
|
|
export function addChanges (changes) {
|
2017-02-28 21:32:23 +00:00
|
|
|
return dispatch => {
|
2017-03-08 00:45:18 +00:00
|
|
|
setTimeout(() => {
|
2017-02-28 21:32:23 +00:00
|
|
|
dispatch(addChangesSync(changes));
|
|
|
|
});
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
export function addChangesSync (changes) {
|
2016-09-22 03:32:12 +00:00
|
|
|
return {type: ENTITY_CHANGES, changes};
|
2016-04-26 07:29:24 +00:00
|
|
|
}
|