import express from 'express'; import React from 'react'; import { StaticRouter } from 'react-router-dom'; import { renderToString } from 'react-dom/server'; import serialize from 'serialize-javascript'; import App from './frontend/app'; import { parseBuildingURL } from './parse'; import { getUserById } from './api/services/user'; import { getBuildingById, getBuildingLikeById, getBuildingUPRNsById, getLatestRevisionId } from './api/services/building'; // reference packed assets const assets = require(process.env.RAZZLE_ASSETS_MANIFEST); function frontendRoute(req: express.Request, res: express.Response) { const context: any = {}; // TODO: remove any const data: any = {}; // TODO: remove any context.status = 200; const userId = req.session.user_id; const buildingId = parseBuildingURL(req.url); const isBuilding = (typeof (buildingId) !== 'undefined'); if (isBuilding && isNaN(buildingId)) { context.status = 404; } Promise.all([ userId ? getUserById(userId) : undefined, isBuilding ? getBuildingById(buildingId) : undefined, isBuilding ? getBuildingUPRNsById(buildingId) : undefined, (isBuilding && userId) ? getBuildingLikeById(buildingId, userId) : false, getLatestRevisionId() ]).then(function ([user, building, uprns, buildingLike, latestRevisionId]) { if (isBuilding && typeof (building) === 'undefined') { context.status = 404; } data.user = user; data.building = building; data.building_like = buildingLike; if (data.building != null) { data.building.uprns = uprns; } data.latestRevisionId = latestRevisionId; renderHTML(context, data, req, res); }).catch(error => { console.error(error); data.user = undefined; data.building = undefined; data.building_like = undefined; data.latestRevisionId = 0; context.status = 500; renderHTML(context, data, req, res); }); } function renderHTML(context, data, req, res) { const markup = renderToString( ); if (context.url) { res.redirect(context.url); } else { res.status(context.status).send( ` Colouring London ${ assets.client.css ? `` : '' } ${ process.env.NODE_ENV === 'production' ? `` : `` }
${markup}
` ); } } export default frontendRoute;