Vulcan/packages/nova-lib/lib/client/render_context.js

53 lines
1.5 KiB
JavaScript
Raw Normal View History

2017-02-08 09:15:09 +08:00
import { browserHistory } from 'react-router';
2017-02-12 22:00:13 +08:00
import { compose } from 'redux';
2017-02-06 14:33:34 +08:00
2017-02-12 22:00:13 +08:00
import {
createApolloClient,
configureStore, STORE_RELOADED,
addAction, getActions, addReducer, getReducers, addMiddleware, getMiddlewares,
Utils,
} from '../modules/index.js';
2017-02-06 14:33:34 +08:00
2017-02-12 22:00:13 +08:00
// init
2017-02-08 09:15:09 +08:00
const history = browserHistory;
2017-02-06 14:33:34 +08:00
const loginToken = global.localStorage['Meteor.loginToken'];
const apolloClient = createApolloClient();
2017-02-12 22:00:13 +08:00
addReducer({ apollo: apolloClient.reducer() });
addMiddleware(apolloClient.middleware());
2017-02-06 14:33:34 +08:00
2017-02-12 22:00:13 +08:00
// init context
const context = {
history,
loginToken,
apolloClient,
addAction, // context.addAction same as addAction
getActions, // context.getActions same as getActions
addReducer, // context.addReducer same as addReducer
getReducers, // context.getReducers same as getReducers
addMiddleware, // context.addMiddleware same as addMiddleware
getMiddlewares, // context.getMiddlewares same as getMiddlewares
};
2017-02-06 14:33:34 +08:00
2017-02-16 10:12:58 +08:00
// init store
2017-02-12 22:00:13 +08:00
context.store = configureStore(context.getReducers, {}, (store) => {
2017-02-16 10:11:22 +08:00
let chain, newDispatch;
2017-02-06 14:33:34 +08:00
return next => (action) => {
2017-02-16 10:11:22 +08:00
if (!chain) {
2017-02-12 22:00:13 +08:00
chain = context.getMiddlewares().map(middleware => middleware(store));
2017-02-16 10:11:22 +08:00
newDispatch = compose(...chain)(next)
2017-02-06 14:33:34 +08:00
}
2017-02-16 10:11:22 +08:00
return newDispatch(action);
2017-02-06 14:33:34 +08:00
};
2017-02-16 10:11:22 +08:00
})
2017-02-06 14:33:34 +08:00
2017-02-12 22:00:13 +08:00
// render context object
export const renderContext = { get: () => context };
2017-02-08 04:36:57 +08:00
2017-02-12 22:00:13 +08:00
// render context get function
2017-02-08 04:36:57 +08:00
export const getRenderContext = () => renderContext.get();
2017-02-08 09:15:09 +08:00
2017-02-12 22:00:13 +08:00
// withRenderContext make it easy to access context
2017-02-08 09:15:09 +08:00
export const withRenderContext = (func) => {
2017-02-12 22:00:13 +08:00
func(context);
2017-02-08 09:15:09 +08:00
};