Skip to content

Instantly share code, notes, and snippets.

@hekike
Created October 30, 2014 20:02
Show Gist options
  • Save hekike/1da7d83fffe04f20abd2 to your computer and use it in GitHub Desktop.
Save hekike/1da7d83fffe04f20abd2 to your computer and use it in GitHub Desktop.
KOA + React = Isomorphic
var _ = require('lodash-node');
var routeConfig = require('./../app/configs/routes');
var serialize = require('serialize-javascript');
/*
* Is react route
*
* @method isReactRoute
* @param {Object} _route
* @return {Boolean}
*/
function isReactRoute (_route) {
return _.some(routeConfig, function (route) {
return _route.path.match(new RegExp(route.path)) &&
route.method.toUpperCase() === _route.method;
});
}
/*
* Share state
*
* @method shareState
* @param {Object} application
* @return {String}
*/
function shareState(application) {
var state = application.context.dehydrate();
var serializedState = serialize(state);
return '(function (root) {\n' +
'root.App || (root.App = {});\n' +
'root.App.Context = ' + serializedState +
';\n }(this));';
}
module.exports.isReactRoute = isReactRoute;
module.exports.shareState = shareState;
/* *
* React page middleware
*/
app.use(function *() {
// Is react route?
if (!routeHelper.isReactRoute({ path: this.path, method: this.method })) {
return;
}
var application = new Application();
var actionContext = application.context.getActionContext();
var executeAction = thunkify(actionContext.executeAction);
var renderedHtml;
// Execute navigation action
try {
yield executeAction(navigateAction, { path: this.url });
} catch (err) {
if(err.status === 404) {
this.throw(404);
}
this.throw(500, 'Error happened.');
}
// React render
renderedHtml = React.renderComponentToString(application.getComponent());
// Render layout with the application state
yield this.render('layout', {
html: renderedHtml,
state: routeHelper.shareState(application)
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment