git ssb

1+

dinoworm ๐Ÿ› / catstack



Tree: 8d668726e7d11fcdfc803f3c47ed305680c7194f

Files: 8d668726e7d11fcdfc803f3c47ed305680c7194f / app / render.js

2538 bytesRaw
1// https://github.com/jlongster/react-redux-universal-hot-example/blob/master/src/server.js
2
3const http =require('http')
4const Url = require('url')
5const React = require('react')
6const { renderToString } = require('react-dom/server')
7const { Provider } = require('react-redux')
8const { createHistory } = require('history')
9const { Router, RoutingContext, match } = require('react-router')
10const sendHtml = require('send-data/html')
11const sendError = require('send-data/error')
12const redirect = require('predirect')
13
14const createStore = require('app/store')
15const routes = require('app/routes')
16const fetchAllData = require('app/util/fetch-all-data')
17
18module.exports = createRender
19
20function createRender (config) {
21 const staticUrl = Url.format(config.static.url)
22
23 return http.createServer(render)
24
25 function render (req, res) {
26 const store = createStore()
27
28 match({
29 routes: routes,
30 location: req.url
31 }, function (err, redirectLocation, renderProps) {
32 if (redirectLocation) {
33 redirect(req, res, redirectLocation.pathname + redirectLocation.search)
34 } else if (err) {
35 sendError(req, res, { body: err })
36 } else if (!renderProps) {
37 sendError(req, res, {
38 statusCode: 404,
39 body: new Error('Not found')
40 })
41 } else {
42 fetchAllData(
43 renderProps.components,
44 store.getState, store.dispatch,
45 renderProps.location,
46 renderProps.params
47 ).then(function () {
48 const component = <Provider store={store} key="provider">
49 <RoutingContext { ...renderProps } />
50 </Provider>
51
52 var innerHtml
53 try {
54 innerHtml = renderToString(component)
55 } catch (err) {
56 return sendError(req, res, { body: err })
57 }
58
59 const html = renderFullPage(innerHtml, store.getState(), config)
60
61 sendHtml(req, res, html)
62 })
63 }
64 })
65 }
66
67 function renderFullPage (innerHtml, initialData) {
68 return `
69 <!DOCTYPE html>
70 <html lang="en">
71 <head>
72 <meta charset="utf-8" />
73 <title>Craftworks TodoMVC</title>
74 <meta name="viewport" content="width=device-width, initial-scale=1" />
75 </head>
76 <body>
77 <main>${ innerHtml }</main>
78 <script>
79 window.__data = ${ JSON.stringify(initialData) }
80 </script>
81 <script src="${Url.resolve(staticUrl, 'bundle.js')}"></script>
82 </body>
83 </html>
84 `
85 }
86}
87
88

Built with git-ssb-web