updux/src/buildUpreducer.js

46 lines
1.1 KiB
JavaScript
Raw Normal View History

2021-10-15 16:41:58 +00:00
import u from 'updeep';
import { mapValues } from 'lodash';
2021-10-07 16:04:15 +00:00
2021-10-18 14:54:28 +00:00
export function buildUpreducer(
initial,
mutations,
subduxes = {},
wrapper = undefined
) {
2021-10-07 16:04:15 +00:00
const subReducers =
Object.keys(subduxes).length > 0
? mapValues(subduxes, ({ upreducer }) => upreducer)
: null;
2021-10-18 14:54:28 +00:00
const upreducer = (action) => (state) => {
2021-10-18 13:02:20 +00:00
if (!action?.type)
throw new Error('upreducer called with a bad action');
2021-10-17 22:41:56 +00:00
2021-10-07 16:04:15 +00:00
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);
};
2021-10-18 14:54:28 +00:00
return wrapper ? wrapper(upreducer) : upreducer;
2021-10-07 16:04:15 +00:00
}