-
Notifications
You must be signed in to change notification settings - Fork 8
/
react-router-middleware.jsx
99 lines (87 loc) · 2.88 KB
/
react-router-middleware.jsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
'use strict';
var React = require('react')
var assign = require('react/lib/Object.assign')
var Router = require('@insin/react-router')
var Redirect = require('@insin/react-router/lib/Redirect')
var {StaticLocation} = Router
var fetchData = require('./utils/fetchData')
var getTitle = require('./utils/getTitle')
module.exports = function(routes, options) {
if (!routes) {
throw new Error('Routes must be provided')
}
options = assign({title: {}}, options)
function renderApp(location, cb) {
var router = Router.create({
location,
routes,
onAbort(reason) {
if (reason instanceof Error) {
cb(reason)
}
else if (reason instanceof Redirect) {
cb(null, router, {redirect: reason})
}
else {
cb(null, router, reason)
}
},
onError(err) {
cb(err)
}
})
router.run((Handler, state) => {
if (state.routes[0].name == 'notFound') {
var html = React.renderToStaticMarkup(<Handler/>)
var title = getTitle(state.routes, {}, {})
return cb(null, router, {notFound: true}, html, null, title)
}
fetchData(state.routes, state.params, (err, fetchedData) => {
var props = assign({}, fetchedData, state.data)
var html = React.renderToString(<Handler {...props}/>)
var title = getTitle(state.routes, state.params, props, options.title)
cb(null, router, null, html, JSON.stringify(props), title)
})
})
}
function renderAppHandler(res, next, err, router, special, html, props, title) { // ಠ_ಠ
if (err) {
return next(err)
}
if (!special) {
return res.render('react', {title, html, props})
}
if (special.notFound) {
res.status(404).render('react-404', {title, html})
}
else if (special.redirect) {
var redirect = special.redirect
var path = router.makePath(redirect.to, redirect.params, redirect.query)
// Rather than introducing a server-specific abort reason object, use the
// fact that a redirect has a data property as an indication that a
// response should be rendered directly.
if (redirect.data) {
renderApp(
new StaticLocation(path, redirect.data),
renderAppHandler.bind(null, res, next)
)
}
else {
res.redirect(303, path)
}
}
else {
console.error('Unexpected special response case: ', special.constructor, special)
next(new Error('Unexpected special response case, see server logs.'))
}
}
return function reactRouter(req, res, next) {
// Provide the method and body of non-GET requests as a request-like object
var data = null
if (req.method != 'GET') {
data = {method: req.method, body: req.body}
}
var location = new StaticLocation(req.url, data)
renderApp(location, renderAppHandler.bind(null, res, next))
}
}