Skip to content

Commit

Permalink
Store management with createStore (#71)
Browse files Browse the repository at this point in the history
* store: `createStore` function.

* store (in progress)

* tests for `createStore`.

* full test coverage for `createStore`.

* backwards compatibility for `createStore`.

* Store should catch and print errors from reducers, if any.

* tests for `createStore` with combined reducers.

* fix for alex -_-

* `combineReducers` with tests.

* initialize Store by firing first init action.

* implement `createStore` everywhere.

* delete now-redundant code.

* drop `redux`.

* append `appName` to dispatched action payloads like before.

* padded pretty date in logs.
  • Loading branch information
fahad19 authored Jan 2, 2017
1 parent 305c87c commit 8900863
Show file tree
Hide file tree
Showing 20 changed files with 770 additions and 357 deletions.
2 changes: 2 additions & 0 deletions .alexignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
node_modules
src/createStore.js
5 changes: 5 additions & 0 deletions .alexrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"allow": [
"destroy"
]
}
1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,6 @@
"lodash": "^4.13.1",
"react": "^0.14.8",
"react-dom": "^0.14.8",
"redux": "^3.5.2",
"rxjs": "^5.0.1"
},
"devDependencies": {
Expand Down
41 changes: 39 additions & 2 deletions src/combineReducers.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,40 @@
import { combineReducers } from 'redux';
/* eslint-disable prefer-template */
export default function combineReducers(reducers, options = {}) {
const keys = Object.keys(reducers);
const opts = {
console: console,
...options,
};

export default combineReducers;
return function rootReducer(state = {}, action) {
let changed = false;

const fullStateTree = {};
keys.forEach(function processReducer(key) {
const reducer = reducers[key];
const previousState = state[key];
let updatedState;

try {
updatedState = reducer(previousState, action);
} catch (reducerError) {
opts.console.error('Reducer for key `' + key + '` threw an error:');
throw reducerError;
}

if (typeof updatedState === 'undefined') {
throw new Error('Reducer for key `' + key + '` returned `undefined`');
}

fullStateTree[key] = updatedState;

if (changed === true || updatedState !== previousState) {
changed = true;
}
});

return changed
? fullStateTree
: state;
};
}
53 changes: 12 additions & 41 deletions src/createApp.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
/* eslint-disable no-console, no-underscore-dangle */
/* globals window */
import { Subject } from 'rxjs';
import { createStore, applyMiddleware, compose } from 'redux';
import _ from 'lodash';

import createAppendActionMiddleware from './middlewares/appendAction';
import createAsyncMiddleware from './middlewares/async';
import createStore from './createStore';
import Provider from './components/Provider';
import h from './h';

Expand Down Expand Up @@ -70,17 +68,6 @@ class BaseApp {
);

this.readableApps = [];

// state$
this._storeSubscription = null;
const store = this._getStore();
const state$ = new Subject();

this._storeSubscription = store.subscribe(() => {
state$.next(store.getState());
});

this.state$ = state$.startWith(store.getState());
}

getRootApp() {
Expand Down Expand Up @@ -131,29 +118,16 @@ class BaseApp {
}

_createStore(rootReducer, initialState = {}) {
const middlewares = [
createAsyncMiddleware({ app: this }),
createAppendActionMiddleware({
key: 'appName',
value: this.getOption('name')
})
];

if (process.env.NODE_ENV !== 'production') {
if (this.getOption('enableLogger') === true) {
const createLogger = require('./middlewares/logger'); // eslint-disable-line

middlewares.push(createLogger());
}
}

this.options.store = createStore(
rootReducer,
const Store = createStore({
reducer: rootReducer,
initialState,
compose(
applyMiddleware(...middlewares)
)
);
enableLogger: this.options.enableLogger,
thunkArgument: { app: this },
appendAction: {
appName: this.options.name,
},
});
this.options.store = new Store();

return this.options.store;
}
Expand Down Expand Up @@ -208,7 +182,7 @@ class BaseApp {
return null;
}

return app.state$;
return app.options.store.getState$();
}

dispatch(action) {
Expand Down Expand Up @@ -250,10 +224,7 @@ class BaseApp {

beforeUnmount() {
const output = this.options.beforeUnmount.bind(this)();

if (typeof this._storeSubscription === 'function') {
this._storeSubscription();
}
this.options.store.destroy();

return output;
}
Expand Down
135 changes: 135 additions & 0 deletions src/createStore.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
/* eslint-disable no-console */
import _ from 'lodash';
import { BehaviorSubject } from 'rxjs';

class BaseStore {
constructor(options = {}) {
this.options = {
initialState: null,
thunkArgument: null,
appendAction: false,
reducer: state => state,
enableLogger: true,
console: console,
...options,
};

this.internalState$ = new BehaviorSubject(this.options.initialState)
.scan((previousState, action) => {
let updatedState;
const d = new Date();
const prettyDate = [
_.padStart(d.getHours(), 2, 0),
':',
_.padStart(d.getMinutes(), 2, 0),
':',
_.padStart(d.getSeconds(), 2, 0),
'.',
_.padStart(d.getMilliseconds(), 3, 0)
].join('');

try {
updatedState = this.options.reducer(previousState, action);
} catch (error) {
if (action && action.type) {
this.options.console.error(`Error processing @ ${prettyDate} ${action.type}:`);
}
this.options.console.error(error);

return previousState;
}

// logger in non-production mode only
if (process.env.NODE_ENV !== 'production') {
if (this.options.enableLogger === true) {
const groupName = `action @ ${prettyDate} ${action.type}`;

if (typeof this.options.console.group === 'function') {
this.options.console.group(groupName);
}

this.options.console.log('%cprevious state', 'color: #9e9e9e; font-weight: bold;', previousState);
this.options.console.log('%caction', 'color: #33c3f0; font-weight: bold;', action);
this.options.console.log('%ccurrent state', 'color: #4cAf50; font-weight: bold;', updatedState);

if (typeof this.options.console.groupEnd === 'function') {
this.options.console.groupEnd();
}
}
}

return updatedState;
});
this.exposedState$ = new BehaviorSubject();

this.cachedState = Object.assign({}, this.options.initialState);
this.subscription = this.internalState$
.subscribe((state) => {
this.cachedState = state;
this.exposedState$.next(state);
});

this.dispatch({ type: '__FRINT_INIT__' });
}

getState$() {
return this.exposedState$;
}

getState = () => {
this.options.console.warn('[DEPRECATED] `Store.getState` has been deprecated, and kept for consistency purpose only with v0.x');

return this.cachedState;
}

dispatch = (action) => {
if (typeof action === 'function') {
return action(
this.dispatch,
this.getState,
this.options.thunkArgument
);
}

const payload = (
this.options.appendAction &&
_.isPlainObject(this.options.appendAction)
)
? { ...this.options.appendAction, ...action }
: action;

return this.internalState$.next(payload);
}

subscribe(callback) {
this.options.console.warn('[DEPRECATED] `Store.subscribe` has been deprecated, and kept for consistency purpose only with v0.x');

const subscription = this.getState$()
.subscribe((state) => {
callback(state);
});

return function unsubscribe() {
subscription.unsubscribe();
};
}

destroy() {
if (this.subscription) {
this.subscription.unsubscribe();
}
}
}

export default function createStore(options = {}) {
class Store extends BaseStore {
constructor(opts = {}) {
super(_.merge(
options,
opts
));
}
}

return Store;
}
2 changes: 2 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import Model from './Model';
import PropTypes from './PropTypes';
import Region from './components/Region';
import render from './render';
import createStore from './createStore';
import isObservable from './utils/isObservable';
import h from './h';

Expand All @@ -19,6 +20,7 @@ export default {
createFactory,
createModel,
createService,
createStore,
mapToProps,
Model,
PropTypes,
Expand Down
18 changes: 0 additions & 18 deletions src/middlewares/appendAction.js

This file was deleted.

19 changes: 0 additions & 19 deletions src/middlewares/async.js

This file was deleted.

44 changes: 0 additions & 44 deletions src/middlewares/logger.js

This file was deleted.

Loading

0 comments on commit 8900863

Please sign in to comment.