Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
80537 views
1
// Render React app
2
import React from 'react';
3
import Router from 'react-router';
4
import FluxComponent from 'flummox/component';
5
import Flux from '../shared/Flux';
6
import routes from '../shared/routes';
7
import performRouteHandlerStaticMethod from '../shared/utils/performRouteHandlerStaticMethod';
8
import nunjucks from 'nunjucks';
9
10
nunjucks.configure('views', {
11
autoescape: true,
12
});
13
14
export default function(app) {
15
app.use(function *() {
16
const router = Router.create({
17
routes: routes,
18
location: this.url,
19
onError: error => {
20
throw error;
21
},
22
onAbort: abortReason => {
23
const error = new Error();
24
25
if (abortReason.constructor.name === 'Redirect') {
26
const { to, params, query } = abortReason;
27
const url = router.makePath(to, params, query);
28
error.redirect = url;
29
}
30
31
throw error;
32
}
33
});
34
35
const flux = new Flux();
36
37
let appString;
38
39
try {
40
const { Handler, state } = yield new Promise((resolve, reject) => {
41
router.run((_Handler, _state) =>
42
resolve({ Handler: _Handler, state: _state })
43
);
44
});
45
46
const routeHandlerInfo = { state, flux };
47
48
try {
49
yield performRouteHandlerStaticMethod(state.routes, 'routerWillRun', routeHandlerInfo);
50
} catch (error) {}
51
52
53
appString = React.renderToString(
54
<FluxComponent flux={flux}>
55
<Handler {...state} />
56
</FluxComponent>
57
);
58
} catch (error) {
59
if (error.redirect) {
60
return this.redirect(error.redirect);
61
}
62
63
throw error;
64
}
65
66
this.body = nunjucks.render('index.html', {
67
appString,
68
env: process.env,
69
});
70
});
71
}
72
73