UNPKG

1.77 kBJavaScriptView Raw
1import {
2 createStore,
3 applyMiddleware,
4} from 'redux';
5import makePropTypesDirective from './directive-proptypes';
6import thunk from 'redux-thunk';
7
8const ActionTypes = {
9 INIT: '@@redux/INIT',
10};
11
12/**
13 *
14 * @param app {{angular}}
15 */
16function angularSetup(app) {
17 /**
18 * understanding angular provider: https://www.evernote.com/shard/s16/sh/93652e36-4492-438d-94e3-86714b8ed49e/d885f65c9a74675c3d22cb4ff1d9df56
19 */
20 app.provider('ngStore', function () { // because we need the context `this`
21 let state = {};
22 let currentUpdater = currentState => currentState;
23 let dispatchLayers = [thunk];
24
25
26 this.setInitialState = initialState => {
27 state = initialState;
28 };
29
30 this.setReducers = this.putUpdaters = updater => {
31 currentUpdater = updater;
32 };
33
34 this.putLayers = layers => {
35 dispatchLayers = layers;
36 };
37
38 this.$get = ['$timeout',
39 function ($timeout) {
40 function digestAngularUI() {
41 return (nextLayer) => (action) => {
42 let result;
43 try {
44 result = nextLayer(action);
45 } catch (e) {
46 console.error('DISPATCH ERROR >>> ', e);
47 }
48
49 // update the UI on angular, make sure changes in state will be in the $digest circle
50 $timeout(() => result);
51 return result;
52 };
53 }
54
55 dispatchLayers.unshift(digestAngularUI);
56
57 const finalStore = createStore(currentUpdater, state, applyMiddleware(...dispatchLayers));
58
59 return finalStore;
60 }];
61 });
62
63
64 app.run(['ngStore', (store) => {
65 store.dispatch({
66 type: ActionTypes.INIT,
67 });
68 }]);
69
70 app.directive = makePropTypesDirective(app.directive.bind(app));
71
72 return app;
73}
74
75export default angularSetup;