2021-10-15 16:41:58 +00:00
|
|
|
import u from 'updeep';
|
|
|
|
import { mapValues } from 'lodash';
|
2021-10-07 16:04:15 +00:00
|
|
|
|
|
|
|
export function buildUpreducer(initial, mutations, subduxes = {}) {
|
|
|
|
const subReducers =
|
|
|
|
Object.keys(subduxes).length > 0
|
|
|
|
? mapValues(subduxes, ({ upreducer }) => upreducer)
|
|
|
|
: null;
|
|
|
|
|
|
|
|
return (action) => (state) => {
|
|
|
|
let newState = state ?? initial;
|
|
|
|
|
|
|
|
if (subReducers) {
|
2021-10-12 13:42:30 +00:00
|
|
|
if (subduxes['*']) {
|
|
|
|
newState = u.updateIn(
|
|
|
|
'*',
|
|
|
|
subduxes['*'].upreducer(action),
|
|
|
|
newState
|
|
|
|
);
|
|
|
|
} else {
|
|
|
|
const update = mapValues(subReducers, (upReducer) =>
|
|
|
|
upReducer(action)
|
|
|
|
);
|
2021-10-07 16:04:15 +00:00
|
|
|
|
2021-10-12 13:42:30 +00:00
|
|
|
newState = u(update, newState);
|
|
|
|
}
|
2021-10-07 16:04:15 +00:00
|
|
|
}
|
|
|
|
|
2021-10-13 17:54:17 +00:00
|
|
|
const a = mutations[action.type] || mutations['+'];
|
2021-10-07 16:04:15 +00:00
|
|
|
|
|
|
|
if (!a) return newState;
|
|
|
|
|
|
|
|
return a(action.payload, action)(newState);
|
|
|
|
};
|
|
|
|
}
|