Files
freeCodeCamp/server/boot/a-react.js

70 lines
2.0 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 12:01:56 -07:00
import debugFactory from 'debug';
2015-07-02 23:44:34 -07:00
import { app$ } from '../../common/app';
2015-06-29 12:01:56 -07:00
import { Cat } from 'thundercats';
2015-06-29 09:50:25 -07:00
2015-06-29 12:01:56 -07:00
const debug = debugFactory('freecc:servereact');
2015-07-01 15:14:10 -07:00
// add routes here as they slowly get reactified
// remove their individual controllers
2015-06-29 12:01:56 -07:00
const routes = [
2015-07-03 20:42:54 -07:00
'/Hikes'
2015-06-29 09:50:25 -07:00
];
2015-06-29 12:01:56 -07:00
export default function reactSubRouter(app) {
2015-07-02 23:44:34 -07:00
var router = app.loopback.Router();
2015-06-29 09:50:25 -07:00
routes.forEach(function(route) {
router.get(route, serveReactApp);
});
app.use(router);
function serveReactApp(req, res, next) {
const fcc = new Cat();
const location = new Location(req.path, req.query)
2015-06-29 09:50:25 -07:00
// returns a router wrapped app
app$(location)
2015-06-29 09:50:25 -07:00
// if react-router does not find a route send down the chain
.filter(function(initialState) {
console.log('initialState', initialState);
/*
2015-06-29 09:50:25 -07:00
var state = data.state;
// this may not work with react-router 1.0.0
var notFound = state.routes.some(route => route.isNotFound);
if (notFound) {
debug('tried to find %s but got 404', state.path);
next();
}
return !notFound;
*/
return true;
2015-06-29 09:50:25 -07:00
})
.flatMap(function(initialState) {
2015-06-29 09:50:25 -07:00
// call thundercats renderToString
// prefetches data and sets up it up for current state
return fcc.renderToString(
React.createElement(Router, initialState[0])
);
2015-06-29 09:50:25 -07:00
})
// makes sure we only get one onNext and closes subscription
.firstOrDefault()
.flatMap(function({ data, markup }) {
2015-06-29 09:50:25 -07:00
debug('react rendered');
res.expose(data, 'data');
2015-06-29 09:50:25 -07:00
// now render jade file with markup injected from react
return res.render$('layout-react', { markup: markup });
2015-06-29 09:50:25 -07:00
})
.subscribe(
function(markup) {
debug('jade rendered');
res.send(markup);
},
next
);
}
2015-06-29 12:01:56 -07:00
}