2019-10-21 21:17:56 +00:00
|
|
|
import fp from 'lodash/fp';
|
|
|
|
import buildActions from './buildActions';
|
|
|
|
import buildInitial from './buildInitial';
|
|
|
|
import buildMutations from './buildMutations';
|
|
|
|
|
|
|
|
import buildCreateStore from './buildCreateStore';
|
|
|
|
import buildMiddleware from './buildMiddleware';
|
|
|
|
import buildUpreducer from './buildUpreducer';
|
2019-10-23 21:47:43 +00:00
|
|
|
import { UpduxConfig, Dictionary, Action, ActionCreator, Mutation, Upreducer } from './types';
|
2019-10-23 18:44:12 +00:00
|
|
|
|
2019-10-23 21:47:43 +00:00
|
|
|
import { Middleware } from 'redux';
|
2019-10-21 21:17:56 +00:00
|
|
|
|
2019-10-23 21:47:43 +00:00
|
|
|
export class Updux<S=any> {
|
2019-10-21 21:17:56 +00:00
|
|
|
|
2019-10-23 17:48:19 +00:00
|
|
|
subduxes: Dictionary<Updux>;
|
|
|
|
|
2019-10-23 18:44:12 +00:00
|
|
|
actions: Dictionary<ActionCreator>
|
|
|
|
|
2019-10-23 21:47:43 +00:00
|
|
|
initial: S;
|
|
|
|
|
|
|
|
mutations: Dictionary<Mutation>;
|
|
|
|
|
|
|
|
upreducer: Upreducer<S>;
|
|
|
|
|
|
|
|
reducer: (state:S|undefined,action:Action) => S;
|
|
|
|
|
|
|
|
middleware: Middleware;
|
|
|
|
|
|
|
|
createStore: Function;
|
|
|
|
|
2019-10-23 17:48:19 +00:00
|
|
|
constructor(config: UpduxConfig) {
|
2019-10-21 21:17:56 +00:00
|
|
|
|
|
|
|
this.subduxes = fp.mapValues(
|
2019-10-23 17:48:19 +00:00
|
|
|
(value:UpduxConfig|Updux) => fp.isPlainObject(value) ? new Updux(value) : value )(fp.getOr({},'subduxes',config)
|
|
|
|
) as Dictionary<Updux>;
|
2019-10-21 21:17:56 +00:00
|
|
|
|
|
|
|
|
|
|
|
this.actions = buildActions(
|
2019-10-22 22:10:45 +00:00
|
|
|
config.actions,
|
2019-10-23 21:47:43 +00:00
|
|
|
[ ...Object.keys(config.mutations||{}), ...Object.keys(config.effects||{} ) ],
|
|
|
|
fp.flatten( Object.values( this.subduxes ).map( ({actions}:Updux) => Object.entries(actions) ) ),
|
2019-10-21 21:17:56 +00:00
|
|
|
)
|
|
|
|
|
2019-10-23 21:47:43 +00:00
|
|
|
this.initial = buildInitial<any>(
|
2019-10-21 21:17:56 +00:00
|
|
|
config.initial, fp.mapValues( ({initial}) => initial )(this.subduxes)
|
|
|
|
);
|
|
|
|
|
|
|
|
this.mutations = buildMutations(
|
|
|
|
config.mutations, this.subduxes
|
|
|
|
);
|
|
|
|
|
|
|
|
this.upreducer = buildUpreducer(
|
|
|
|
this.initial, this.mutations
|
|
|
|
);
|
|
|
|
|
|
|
|
this.reducer = (state,action) => {
|
2019-10-23 21:47:43 +00:00
|
|
|
return this.upreducer(action)(state as S);
|
2019-10-21 21:17:56 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
this.middleware = buildMiddleware(
|
|
|
|
config.effects,
|
|
|
|
this.actions,
|
2019-10-23 21:47:43 +00:00
|
|
|
Object.values(this.subduxes).map( sd => sd.middleware )
|
2019-10-21 21:17:56 +00:00
|
|
|
);
|
|
|
|
|
2019-10-23 21:47:43 +00:00
|
|
|
this.createStore = buildCreateStore<S>(this.reducer,this.initial,this.middleware,this.actions);
|
2019-10-21 21:17:56 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
export default Updux;
|