Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update middleware api #213

Merged
merged 3 commits into from
Jul 8, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 2 additions & 26 deletions src/createStore.js
Original file line number Diff line number Diff line change
@@ -1,42 +1,18 @@
import Store from './Store';
import composeReducers from './utils/composeReducers';
import composeMiddleware from './utils/composeMiddleware';
import thunkMiddleware from './middleware/thunk';

const defaultMiddlewares = ({ dispatch, getState }) => [
thunkMiddleware({ dispatch, getState })
];

export default function createStore(
reducer,
initialState,
middlewares = defaultMiddlewares
initialState
) {
const finalReducer = typeof reducer === 'function' ?
reducer :
composeReducers(reducer);

const store = new Store(finalReducer, initialState);
const getState = ::store.getState;

const rawDispatch = ::store.dispatch;
let cookedDispatch = null;

function dispatch(action) {
return cookedDispatch(action);
}

const finalMiddlewares = typeof middlewares === 'function' ?
middlewares({ dispatch, getState }) :
middlewares;

cookedDispatch = composeMiddleware(
...finalMiddlewares,
rawDispatch
);

return {
dispatch: cookedDispatch,
dispatch: ::store.dispatch,
subscribe: ::store.subscribe,
getState: ::store.getState,
getReducer: ::store.getReducer,
Expand Down
10 changes: 7 additions & 3 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,17 @@
import createStore from './createStore';

// Utilities
import composeMiddleware from './utils/composeMiddleware';
import compose from './utils/compose';
import composeReducers from './utils/composeReducers';
import bindActionCreators from './utils/bindActionCreators';
import applyMiddleware from './utils/applyMiddleware';
import composeMiddleware from './utils/composeMiddleware';

export {
createStore,
composeMiddleware,
compose,
composeReducers,
bindActionCreators
bindActionCreators,
applyMiddleware,
composeMiddleware
};
2 changes: 1 addition & 1 deletion src/middleware/thunk.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
export default function thunkMiddleware({ dispatch, getState }) {
return (next) => (action) =>
return next => action =>
typeof action === 'function' ?
action(dispatch, getState) :
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we consider having the default thunk middleware send the same methods type object to action instead of splitting them into separate parameters like this? i.e.

action({ dispatch, getState })

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I thought about that, too, but 9 times out of 10 a thunk just needs dispatch(), and single argument form is easier.

next(action);
Expand Down
31 changes: 31 additions & 0 deletions src/utils/applyMiddleware.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import compose from './compose';
import composeMiddleware from './composeMiddleware';
import thunk from '../middleware/thunk';

/**
* Creates a higher-order store that applies middleware to a store's dispatch.
* Because middleware is potentially asynchronous, this should be the first
* higher-order store in the composition chain.
* @param {...Function} ...middlewares
* @return {Function} A higher-order store
*/
export default function applyMiddleware(...middlewares) {
const finalMiddlewares = middlewares.length ?
middlewares :
[thunk];

return next => (...args) => {
const store = next(...args);
const methods = {
dispatch: store.dispatch,
getState: store.getState
};
return {
...store,
dispatch: compose(
composeMiddleware(...finalMiddlewares)(methods),
store.dispatch
)
};
};
}
8 changes: 8 additions & 0 deletions src/utils/compose.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
/**
* Composes functions from left to right
* @param {...Function} funcs - Functions to compose
* @return {Function}
*/
export default function compose(...funcs) {
return funcs.reduceRight((composed, f) => f(composed));
}
9 changes: 8 additions & 1 deletion src/utils/composeMiddleware.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,10 @@
import compose from './compose';

/**
* Compose middleware from left to right
* @param {...Function} middlewares
* @return {Function}
*/
export default function composeMiddleware(...middlewares) {
return middlewares.reduceRight((composed, m) => m(composed));
return methods => next => compose(...middlewares.map(m => m(methods)), next);
}
65 changes: 65 additions & 0 deletions test/applyMiddleware.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import expect from 'expect';
import { createStore, applyMiddleware } from '../src/index';
import * as reducers from './helpers/reducers';
import { addTodo, addTodoAsync, addTodoIfEmpty } from './helpers/actionCreators';
import thunk from '../src/middleware/thunk';

describe('applyMiddleware', () => {
it('wraps dispatch method with middleware', () => {
function test(spy) {
return methods => next => action => {
spy(methods);
return next(action);
};
}

const spy = expect.createSpy(() => {});
const store = applyMiddleware(test(spy), thunk)(createStore)(reducers.todos);
store.dispatch(addTodo('Use Redux'));

expect(Object.keys(spy.calls[0].arguments[0])).toEqual([
'dispatch',
'getState'
]);
expect(store.getState()).toEqual([ { id: 1, text: 'Use Redux' } ]);
});

it('uses thunk middleware by default', done => {
const store = applyMiddleware()(createStore)(reducers.todos);

store.dispatch(addTodoIfEmpty('Hello'));
expect(store.getState()).toEqual([{
id: 1,
text: 'Hello'
}]);

store.dispatch(addTodoIfEmpty('Hello'));
expect(store.getState()).toEqual([{
id: 1,
text: 'Hello'
}]);

store.dispatch(addTodo('World'));
expect(store.getState()).toEqual([{
id: 1,
text: 'Hello'
}, {
id: 2,
text: 'World'
}]);

store.dispatch(addTodoAsync('Maybe')).then(() => {
expect(store.getState()).toEqual([{
id: 1,
text: 'Hello'
}, {
id: 2,
text: 'World'
}, {
id: 3,
text: 'Maybe'
}]);
done();
});
});
});
17 changes: 17 additions & 0 deletions test/compose.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import expect from 'expect';
import { compose } from '../src';

describe('Utils', () => {
describe('compose', () => {
it('composes functions from left to right', () => {
const a = next => x => next(x + 'a');
const b = next => x => next(x + 'b');
const c = next => x => next(x + 'c');
const final = x => x;

expect(compose(a, b, c, final)('')).toBe('abc');
expect(compose(b, c, a, final)('')).toBe('bca');
expect(compose(c, a, b, final)('')).toBe('cab');
});
});
});
14 changes: 7 additions & 7 deletions test/composeMiddleware.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,15 @@ import { composeMiddleware } from '../src';

describe('Utils', () => {
describe('composeMiddleware', () => {
it('should return the combined middleware that executes from left to right', () => {
const a = next => action => next(action + 'a');
const b = next => action => next(action + 'b');
const c = next => action => next(action + 'c');
it('should return combined middleware that executes from left to right', () => {
const a = () => next => action => next(action + 'a');
const b = () => next => action => next(action + 'b');
const c = () => next => action => next(action + 'c');
const dispatch = action => action;

expect(composeMiddleware(a, b, c, dispatch)('')).toBe('abc');
expect(composeMiddleware(b, c, a, dispatch)('')).toBe('bca');
expect(composeMiddleware(c, a, b, dispatch)('')).toBe('cab');
expect(composeMiddleware(a, b, c)()(dispatch)('')).toBe('abc');
expect(composeMiddleware(b, c, a)()(dispatch)('')).toBe('bca');
expect(composeMiddleware(c, a, b)()(dispatch)('')).toBe('cab');
});
});
});
75 changes: 1 addition & 74 deletions test/createStore.spec.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import expect from 'expect';
import { createStore } from '../src/index';
import * as reducers from './helpers/reducers';
import { addTodo, addTodoIfEmpty, addTodoAsync } from './helpers/actionCreators';
import { addTodo, addTodoAsync } from './helpers/actionCreators';

describe('createStore', () => {
it('should expose the public API', () => {
Expand Down Expand Up @@ -35,44 +35,6 @@ describe('createStore', () => {
}]);
});

it('should provide the thunk middleware by default', done => {
const store = createStore(reducers.todos);
store.dispatch(addTodoIfEmpty('Hello'));
expect(store.getState()).toEqual([{
id: 1,
text: 'Hello'
}]);

store.dispatch(addTodoIfEmpty('Hello'));
expect(store.getState()).toEqual([{
id: 1,
text: 'Hello'
}]);

store.dispatch(addTodo('World'));
expect(store.getState()).toEqual([{
id: 1,
text: 'Hello'
}, {
id: 2,
text: 'World'
}]);

store.dispatch(addTodoAsync('Maybe')).then(() => {
expect(store.getState()).toEqual([{
id: 1,
text: 'Hello'
}, {
id: 2,
text: 'World'
}, {
id: 3,
text: 'Maybe'
}]);
done();
});
});

it('should dispatch the raw action without the middleware', () => {
const store = createStore(reducers.todos, undefined, []);
store.dispatch(addTodo('Hello'));
Expand Down Expand Up @@ -110,39 +72,4 @@ describe('createStore', () => {
bar: 2
});
});

it('should support custom dumb middleware', done => {
const doneMiddleware = next => action => {
next(action);
done();
};

const store = createStore(
reducers.todos,
undefined,
[doneMiddleware]
);
store.dispatch(addTodo('Hello'));
});

it('should support custom smart middleware', done => {
function doneMiddleware({ getState, dispatch }) {
return next => action => {
next(action);

if (getState().length < 10) {
dispatch(action);
} else {
done();
}
};
}

const store = createStore(
reducers.todos,
undefined,
({ getState, dispatch }) => [doneMiddleware({ getState, dispatch })]
);
store.dispatch(addTodo('Hello'));
});
});