freeCodeCamp/server/boot/a-react.js

65 lines
1.8 KiB
JavaScript
Raw Normal View History

import React from 'react';
import Router from 'react-router';
import Location from 'react-router/lib/Location';
2015-06-29 19:01:56 +00:00
import debugFactory from 'debug';
2015-07-03 06:44:34 +00:00
import { app$ } from '../../common/app';
import { RenderToString } from 'thundercats-react';
2015-06-29 16:50:25 +00:00
2015-06-29 19:01:56 +00:00
const debug = debugFactory('freecc:servereact');
2015-07-01 22:14:10 +00:00
// add routes here as they slowly get reactified
// remove their individual controllers
2015-06-29 19:01:56 +00:00
const routes = [
2015-07-15 06:44:21 +00:00
'/hikes',
'/hikes/*',
2015-07-04 04:46:22 +00:00
'/jobs'
2015-06-29 16:50:25 +00:00
];
2015-06-29 19:01:56 +00:00
export default function reactSubRouter(app) {
2015-07-03 06:44:34 +00:00
var router = app.loopback.Router();
2015-06-29 16:50:25 +00:00
routes.forEach(function(route) {
router.get(route, serveReactApp);
});
app.use(router);
function serveReactApp(req, res, next) {
2015-07-09 05:53:26 +00:00
const location = new Location(req.path, req.query);
2015-06-29 16:50:25 +00:00
// returns a router wrapped app
app$(location)
2015-06-29 16:50:25 +00:00
// if react-router does not find a route send down the chain
.filter(function({ initialState }) {
2015-07-04 04:46:22 +00:00
if (!initialState) {
debug('react tried to find %s but got 404', location.pathname);
2015-07-04 04:46:22 +00:00
return next();
2015-06-29 16:50:25 +00:00
}
2015-07-04 04:46:22 +00:00
return !!initialState;
2015-06-29 16:50:25 +00:00
})
.flatMap(function({ initialState, AppCat }) {
2015-06-29 16:50:25 +00:00
// call thundercats renderToString
// prefetches data and sets up it up for current state
debug('rendering to string');
return RenderToString(
AppCat(),
2015-07-04 04:46:22 +00:00
React.createElement(Router, initialState)
);
2015-06-29 16:50:25 +00:00
})
// makes sure we only get one onNext and closes subscription
.flatMap(function({ data, markup }) {
2015-06-29 16:50:25 +00:00
debug('react rendered');
res.expose(data, 'data');
2015-06-29 16:50:25 +00:00
// now render jade file with markup injected from react
return res.render$('layout-react', { markup: markup });
2015-06-29 16:50:25 +00:00
})
.subscribe(
function(markup) {
debug('jade rendered');
res.send(markup);
},
next
);
}
2015-06-29 19:01:56 +00:00
}