Guest User

Untitled

a guest
Jul 1st, 2016
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.58 KB | None | 0 0
  1. /**
  2. * We are going to use hapi to server side render our application.
  3. * Inspired by: https://github.com/luandro/hapi-universal-redux
  4. *
  5. *
  6. * Created December 11th, 2015
  7. * @author: ywarezk
  8. * @version: 0.18
  9. *
  10. */
  11.  
  12. /*******************
  13. * begin imports
  14. *******************/
  15.  
  16. console.log('1');
  17.  
  18. import {Server} from "hapi";
  19. import h2o2 from "h2o2";
  20. import inert from "inert";
  21. import React from "react";
  22. import ReactDOM from "react-dom/server";
  23. import {RouterContext, match} from "react-router";
  24. import createLocation from "history/lib/createLocation";
  25. import configureStore from "../app/redux/store/configureStore";
  26. import { Provider } from 'react-redux';
  27. import routesContainer from "../app/routes/index";
  28. import url from "url";
  29. const fs = require('fs');
  30. // const paths = (__dirname + '/../public/index.html');
  31. let routes = routesContainer;
  32.  
  33.  
  34. /*******************
  35. * end imports
  36. *******************/
  37.  
  38.  
  39. //redux store and state we might have to dispatch stuff according to the url we are rendering
  40. const store = configureStore();
  41. const initialState = store.getState();
  42.  
  43. //from environment variable grab our data and the backend data
  44. const hostname = process.env.HOSTNAME || "localhost";
  45. const restHostUrl = process.env.SERVER_URL || "localhost";
  46. const restHostProtocol = process.env.SERVER_PROTOCOL || "http";
  47. const restHostPort = process.env.SERVER_PROTOCOL || "1337";
  48.  
  49. //creating hapi server - popping my cherry with hapi on this one - im more of an express kinda guy.
  50. const server = new Server();
  51. server.connection({host: hostname, port: process.env.PORT || 8000});
  52. server.register(
  53. [
  54. h2o2,
  55. inert,
  56. // WebpackPlugin
  57. ],
  58. (err) => {
  59. if (err) {
  60. throw err;
  61. }
  62.  
  63. server.start(() => {
  64. console.info("==> ✅ Server is listening");
  65. console.info("==> 🌎 Go to " + server.info.uri.toLowerCase());
  66. });
  67. });
  68.  
  69. //serve static files
  70. server.route({
  71. method: "GET",
  72. path: "/{params*}",
  73. handler: {
  74. file: (request) => "static" + request.path
  75. }
  76. });
  77.  
  78. //proxy my server urls
  79. server.route({
  80. method: "GET",
  81. path: "/api/{path*}",
  82. handler: {
  83. proxy: {
  84. passThrough: true,
  85. mapUri (request, callback) {
  86. callback(null, url.format({
  87. protocol: restHostProtocol,
  88. host: restHostUrl,
  89. pathname: request.params.path,
  90. query: request.query,
  91. port: restHostPort
  92. }));
  93. },
  94. onResponse (err, res, request, reply, settings, ttl) {
  95. reply(res);
  96. }
  97. }
  98. }
  99. });
  100.  
  101. //these are dynamic requests i need to render
  102. server.ext("onPreResponse", (request, reply) => {
  103.  
  104. match({routes: routes, location: request.path}, (error, redirectLocation, renderProps) => {
  105. console.log(routes);
  106.  
  107. if (redirectLocation) {
  108. reply.redirect(redirectLocation.pathname + redirectLocation.search)
  109. }
  110. else if (error || !renderProps) {
  111. reply.continue();
  112. }
  113. else {
  114. console.log(renderProps);
  115. //router rendering
  116. const reactString = ReactDOM.renderToString(
  117. <Provider store={store}>
  118. <RouterContext {...renderProps} />
  119. </Provider>
  120. );
  121. const webserver = __PRODUCTION__ ? "" : `//${hostname}:8080`;
  122.  
  123. let output = (
  124. `<!doctype html>
  125. <html lang="en-us">
  126. <head>
  127. <meta charset="utf-8">
  128. <title>Hapi Universal Redux</title>
  129. <link rel="shortcut icon" href="/favicon.ico">
  130. <link rel="stylesheet" href="${webserver}/static/dist/client.css" />
  131. </head>
  132. <body>
  133. <div id="root">${reactString}</div>
  134. <script>
  135. window.__INITIAL_STATE__ = ${JSON.stringify(initialState)}
  136. window.__UA__ = ${JSON.stringify(request.headers['user-agent'])}
  137. </script>
  138. <script src=${webserver}/dist/client.js></script>
  139. </body>
  140. </html>`
  141. );
  142.  
  143. //grab the index file from dist and serve the index content with what we rendered
  144. // const template = fs.readFileSync(paths, 'utf-8');
  145. // const injectedManifest = template.replace(
  146. // new RegExp(`<div id="root">`),
  147. // `<div id="root">` + reactString
  148. // );
  149. console.log(output);
  150. reply(output);
  151.  
  152. }
  153. });
  154. });
  155.  
  156. if (__DEV__) {
  157. if (module.hot) {
  158. console.log("[HMR] Waiting for server-side updates");
  159.  
  160. module.hot.accept("../app/routes/index", () => {
  161. routes = require("../app/routes/index");
  162. });
  163.  
  164. module.hot.addStatusHandler((status) => {
  165. if (status === "abort") {
  166. setTimeout(() => process.exit(0), 0);
  167. }
  168. });
  169. }
  170. }
Add Comment
Please, Sign In to add comment