git ssb

1+

dinoworm ๐Ÿ› / catstack



Tree: 2feb98c1e6e7d51eb76ec441dc2a134829471edd

Files: 2feb98c1e6e7d51eb76ec441dc2a134829471edd / app / render.js

2489 bytesRaw
1// https://github.com/jlongster/react-redux-universal-hot-example/blob/master/src/server.js
2
3import http from 'http'
4import Url from 'url'
5import React from 'react'
6import { renderToString } from 'react-dom/server'
7import { Provider } from 'react-redux'
8import { createHistory } from 'history'
9import { Router, RoutingContext, match } from 'react-router'
10import sendHtml from 'send-data/html'
11import sendError from 'send-data/error'
12import redirect from 'predirect'
13
14import createStore from 'app/store'
15import routes from 'app/routes'
16import fetchAllData from 'app/util/fetch-all-data'
17
18export default module.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