|
| 1 | +require('babel-register')({ |
| 2 | + extensions: ['.js'], |
| 3 | + presets: ['es2015'], |
| 4 | +}) |
| 5 | +require('ignore-styles') |
| 6 | +const express = require('express') |
| 7 | +const { createElement } = require('react') |
| 8 | +const { StaticRouter } = require('react-router') |
| 9 | +const { Provider } = require('react-redux') |
| 10 | +const { renderToString } = require('react-dom/server') |
| 11 | + |
| 12 | +const { htmlTemplate } = require('./src/index.html.js') |
| 13 | +const manifest = require('./build/manifest.json') |
| 14 | +const App = require('./src/components/app/app').default |
| 15 | +const storeFactory = require('./src/store').default |
| 16 | + |
| 17 | +const app = express() |
| 18 | +const htmlCache = {} |
| 19 | + |
| 20 | +function makeCacheObject (html, expires = 3600000) { |
| 21 | + return { |
| 22 | + html, |
| 23 | + expires, |
| 24 | + createdAt: Date.now(), |
| 25 | + } |
| 26 | +} |
| 27 | + |
| 28 | +function isFresh (cacheObj) { |
| 29 | + return (Date.now() - cacheObj.createdAt) < cacheObj.expires |
| 30 | +} |
| 31 | + |
| 32 | +function bootstrapApp(location, store) { |
| 33 | + const context = {} |
| 34 | + const appEntry = createElement( |
| 35 | + Provider, { store }, createElement( |
| 36 | + StaticRouter, { location, context }, createElement( |
| 37 | + App))) |
| 38 | + |
| 39 | + const appHTML = renderToString(appEntry) |
| 40 | + return { appHTML, context } |
| 41 | +} |
| 42 | + |
| 43 | +function checkCache(request, response, next) { |
| 44 | + if (htmlCache[request.url] && isFresh(htmlCache[request.url])) { |
| 45 | + response.send(htmlCache[request.url].html) |
| 46 | + return |
| 47 | + } |
| 48 | + |
| 49 | + next() |
| 50 | +} |
| 51 | + |
| 52 | +function handleSSRRequest (request, response) { |
| 53 | + const store = storeFactory() |
| 54 | + const unsubscribe = store.subscribe(() => { |
| 55 | + const state = store.getState() |
| 56 | + if (!state.robotData.isPending) { |
| 57 | + unsubscribe() |
| 58 | + const { appHTML } = bootstrapApp(request.url, store) |
| 59 | + const htmlResponse = htmlTemplate({ |
| 60 | + jsPath: manifest['main.js'], |
| 61 | + cssPath: manifest['main.css'], |
| 62 | + appHTML, |
| 63 | + state, |
| 64 | + }) |
| 65 | + response.send(htmlResponse) |
| 66 | + htmlCache[request.url] = makeCacheObject(htmlResponse) |
| 67 | + } |
| 68 | + }) |
| 69 | + |
| 70 | + const { context } = bootstrapApp(request.url, store) |
| 71 | + if (context.url) { |
| 72 | + response.redirect(context.url) |
| 73 | + unsubscribe() |
| 74 | + return |
| 75 | + } |
| 76 | + store.dispatch({ type: 'INIT_SSR' }) |
| 77 | +} |
| 78 | + |
| 79 | +app.use('/static', express.static('./build/static')) |
| 80 | +app.use(checkCache) |
| 81 | +app.use(handleSSRRequest) |
| 82 | + |
| 83 | +app.listen(8080) |
0 commit comments