1 | import {createStore, applyMiddleware} from 'redux';
|
2 | import createSagaMiddleware from "redux-saga";
|
3 | import {recursiveEnhanceFun} from 'dura-util'
|
4 | import PluginHandler from './PluginHandler'
|
5 | import ModelHandler from './ModelHandler'
|
6 | import invariant from "invariant";
|
7 |
|
8 | const defaultOptions = {
|
9 | initialModel: []
|
10 | }
|
11 |
|
12 | function createDuraCore(options = defaultOptions) {
|
13 |
|
14 | const newOps = {...defaultOptions, ...options}
|
15 |
|
16 | const pluginHandler = new PluginHandler();
|
17 |
|
18 | const modelHandler = new ModelHandler({
|
19 | pluginHandler
|
20 | });
|
21 |
|
22 | const duraCore = {
|
23 | _initialModel: newOps.initialModel,
|
24 | _reduxStore: undefined,
|
25 | _reduxSaga: undefined,
|
26 | _namespaces: {},
|
27 | addModel: addModel,
|
28 | delModel: delModel,
|
29 | addPlugin: addPlugin,
|
30 | start: start,
|
31 | restart: restart
|
32 | }
|
33 |
|
34 | return duraCore;
|
35 |
|
36 | function validate(target) {
|
37 | const {namespace} = target
|
38 |
|
39 | invariant(namespace, `namespace should be defined`)
|
40 |
|
41 | invariant(typeof namespace === 'string', `namespace should be string`)
|
42 |
|
43 | invariant(
|
44 | !duraCore._namespaces[namespace],
|
45 | `namespace should be unique , the repeated namespace is ${namespace}`
|
46 | )
|
47 | }
|
48 |
|
49 | function addPlugin(...plugins) {
|
50 | plugins.forEach(plugin => {
|
51 | validate(plugin)
|
52 | duraCore._namespaces[plugin.namespace] = plugin
|
53 | pluginHandler.addPlugin(plugin)
|
54 | })
|
55 | }
|
56 |
|
57 | function addModel(...models) {
|
58 | models.forEach(model => {
|
59 | validate(model)
|
60 | duraCore._namespaces[model.namespace] = model
|
61 | modelHandler.addModel(model)
|
62 | })
|
63 | }
|
64 |
|
65 | function delModel(...namespaces) {
|
66 | namespaces.forEach(namespace => {
|
67 | delete duraCore._namespaces[namespace]
|
68 | modelHandler.delModel(namespace)
|
69 | });
|
70 | }
|
71 |
|
72 | function start() {
|
73 |
|
74 | duraCore._reduxSaga = createSagaMiddleware();
|
75 | duraCore._reduxStore = createStore(
|
76 | modelHandler.getCombineReducers(),
|
77 | applyMiddleware(duraCore._reduxSaga)
|
78 | )
|
79 | const onStateChangeEventFuns = pluginHandler.getOnStateChangeEventFun();
|
80 | for (const fun of onStateChangeEventFuns) {
|
81 | duraCore._reduxStore.subscribe(() => {
|
82 | fun(duraCore._reduxStore.getState())
|
83 | })
|
84 | }
|
85 | duraCore._reduxSaga.run(modelHandler.getCombineEffects())
|
86 | }
|
87 |
|
88 | function restart() {
|
89 |
|
90 | const {_reduxStore, _reduxSaga} = duraCore
|
91 |
|
92 | _reduxStore.replaceReducer(modelHandler.getCombineReducers());
|
93 | _reduxStore.dispatch({type: '@@duraCore/reducers/onChangeState'})
|
94 | _reduxStore.dispatch({type: '@@dura/cancel'})
|
95 | _reduxSaga.run(modelHandler.getCombineEffects())
|
96 |
|
97 | }
|
98 |
|
99 | }
|
100 |
|
101 | export {
|
102 | createDuraCore
|
103 | } |
\ | No newline at end of file |