updux/dist/actions.js

41 lines
1.5 KiB
JavaScript

import { createAction } from '@reduxjs/toolkit';
import { D } from '@mobily/ts-belt';
export { createAction } from '@reduxjs/toolkit';
export function withPayload(prepare = (input) => input) {
return (...input) => ({
payload: prepare.apply(null, input),
});
}
export function buildActions(localActions = {}, subduxes = {}) {
localActions = D.mapWithKey(localActions, (key, value) => expandAction(value, String(key)));
let actions = {};
for (const slice in subduxes) {
const subdux = subduxes[slice].actions;
if (!subdux)
continue;
for (const a in subdux) {
if (actions[a] && subduxes[actions[a]].actions[a] !== subdux[a]) {
throw new Error(`action '${a}' defined both in subduxes '${actions[a]}' and '${slice}'`);
}
actions[a] = slice;
}
for (const a in localActions) {
if (actions[a]) {
throw new Error(`action '${a}' defined both locally and in subdux '${actions[a]}'`);
}
}
}
return [
localActions,
...D.values(subduxes).map((s) => { var _a; return (_a = s.actions) !== null && _a !== void 0 ? _a : {}; }),
].reduce(D.merge);
}
export function expandAction(prepare, actionType) {
if (typeof prepare === 'function' && prepare.type)
return prepare;
if (typeof prepare === 'function')
return createAction(actionType, withPayload(prepare));
if (actionType)
return createAction(actionType);
}