import React from 'react' import { renderToString } from 'react-dom/server' import { StaticRouter as Router, matchPath } from 'react-router-dom' import { App } from '../components' import routes from './routes' import serialize from 'serialize-javascript' import manifest from '../../public/static/manifest.json' export class ServerRenderer { constructor (head, config) { this.head = head this.config = config } render (req, res, next) { const activeRoute = routes.find((route) => matchPath(req.url, route)) || false const head = this.head const config = this.config if (!activeRoute) { const context = [{}, config] const markup = renderToString( ) res.status(404).send(renderFullPage(markup, head, {}, config)) } else { const promise = activeRoute.getData ? activeRoute.getData(req.path) : Promise.resolve() promise.then((data) => { const context = [data, config] const markup = renderToString( ) res.status(200).send(renderFullPage(markup, head, data, config)) }).catch(next) } } } function renderFullPage (html, head, data, config) { const initialData = [data, config] return ` ${config.title} ${head.scripts.join('\n')}
${html}
` }