Vulcan/packages/nova-lib/lib/client/render_context.js
2017-02-12 22:00:13 +08:00

51 lines
1.6 KiB
JavaScript

import { browserHistory } from 'react-router';
import { compose } from 'redux';
import {
createApolloClient,
configureStore, STORE_RELOADED,
addAction, getActions, addReducer, getReducers, addMiddleware, getMiddlewares,
Utils,
} from '../modules/index.js';
// init
const history = browserHistory;
const loginToken = global.localStorage['Meteor.loginToken'];
const apolloClient = createApolloClient();
addReducer({ apollo: apolloClient.reducer() });
addMiddleware(Utils.defineName(apolloClient.middleware(), 'apolloClientMiddleware'));
// 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
};
// init store **Notes it will reload**
context.store = configureStore(context.getReducers, {}, (store) => {
let chain;
return next => (action) => {
if (!chain || action.type === STORE_RELOADED) {
chain = context.getMiddlewares().map(middleware => middleware(store));
}
return compose(...chain)(next)(action);
};
}).reload({ message: 'init store' });
// render context object
export const renderContext = { get: () => context };
// render context get function
export const getRenderContext = () => renderContext.get();
// withRenderContext make it easy to access context
export const withRenderContext = (func) => {
func(context);
};