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

67 lines
1.7 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,
2017-02-12 22:00:13 +08:00
addAction, getActions, addReducer, getReducers, addMiddleware, getMiddlewares,
} from '../modules/index.js';
2017-02-06 14:33:34 +08:00
let context;
2017-02-06 14:33:34 +08:00
export const initContext = () => {
// init
const history = browserHistory;
const loginToken = global.localStorage['Meteor.loginToken'];
const apolloClient = createApolloClient();
addReducer({ apollo: apolloClient.reducer() });
addMiddleware(apolloClient.middleware());
// init context
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
};
// init store
context.store = configureStore(context.getReducers, {}, (store) => {
let chain, newDispatch;
return next => (action) => {
if (!chain) {
chain = context.getMiddlewares().map(middleware => middleware(store));
newDispatch = compose(...chain)(next)
}
return newDispatch(action);
};
})
}
2017-02-06 14:33:34 +08:00
2017-02-12 22:00:13 +08:00
// render context object
export const renderContext = {
get: () => {
if (typeof context === 'undefined') {
initContext();
}
return 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
};