The approach and the client side code you can find here: https://github.com/yahoo/flux-examples/blob/master/routing/app.js
Created
October 30, 2014 20:02
-
-
Save hekike/1da7d83fffe04f20abd2 to your computer and use it in GitHub Desktop.
KOA + React = Isomorphic
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* * | |
* 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