colouring-montreal/app/src/server.tsx

165 lines
4.7 KiB
TypeScript
Raw Normal View History

2018-09-30 14:50:09 -04:00
/**
* Server-side Express application
* - API methods
* - entry-point to shared React App
*
*/
import React from 'react';
import { StaticRouter } from 'react-router-dom';
import express from 'express';
import { renderToString } from 'react-dom/server';
import serialize from 'serialize-javascript';
2019-02-24 14:28:11 -05:00
import bodyParser from 'body-parser';
2018-09-13 14:54:16 -04:00
import session from 'express-session';
import pgConnect from 'connect-pg-simple';
import App from './frontend/app';
2018-09-30 11:18:57 -04:00
import db from './db';
2019-08-14 05:54:13 -04:00
import { getUserById } from './api/services/user';
2019-01-22 12:02:03 -05:00
import {
getBuildingById,
getBuildingLikeById,
2019-08-14 05:54:13 -04:00
getBuildingUPRNsById
} from './api/services/building';
2019-02-24 07:17:59 -05:00
import tileserver from './tiles/tileserver';
2019-08-14 05:54:13 -04:00
import apiRouter from './api/api';
2018-09-13 15:36:14 -04:00
import { parseBuildingURL } from './parse';
// create server
const server = express();
// reference packed assets
const assets = require(process.env.RAZZLE_ASSETS_MANIFEST);
// disable header
server.disable('x-powered-by');
// serve static files
server.use(express.static(process.env.RAZZLE_PUBLIC_DIR));
// parse POSTed json body
server.use(bodyParser.json());
// handle user sessions
2018-09-13 14:54:16 -04:00
const pgSession = pgConnect(session);
const sess: any = { // TODO: remove any
name: 'cl.session',
store: new pgSession({
2018-09-30 11:18:57 -04:00
pgPromise: db,
2019-02-24 14:28:11 -05:00
tableName: 'user_sessions'
}),
secret: process.env.APP_COOKIE_SECRET,
saveUninitialized: false,
resave: false,
cookie: { maxAge: 30 * 24 * 60 * 60 * 1000 } // 30 days
};
if (server.get('env') === 'production') {
// trust first proxy
server.set('trust proxy', 1)
// serve secure cookies
sess.cookie.secure = true
}
server.use(session(sess));
// handle HTML routes (server-side rendered React)
server.get('/*.html', frontendRoute);
server.get('/', frontendRoute);
function frontendRoute(req, res) {
const context: any = {}; // TODO: remove any
const data: any = {}; // TODO: remove any
2018-09-13 15:41:42 -04:00
context.status = 200;
2018-09-10 18:32:56 -04:00
2019-05-27 13:26:29 -04:00
const userId = req.session.user_id;
const buildingId = parseBuildingURL(req.url);
const isBuilding = (typeof (buildingId) !== 'undefined');
if (isBuilding && isNaN(buildingId)) {
2018-09-13 15:41:42 -04:00
context.status = 404;
}
2018-09-11 18:30:17 -04:00
Promise.all([
2019-05-27 13:26:29 -04:00
userId ? getUserById(userId) : undefined,
isBuilding ? getBuildingById(buildingId) : undefined,
isBuilding ? getBuildingUPRNsById(buildingId) : undefined,
(isBuilding && userId) ? getBuildingLikeById(buildingId, userId) : false
2019-02-24 14:28:11 -05:00
]).then(function (values) {
2018-09-11 18:30:17 -04:00
const user = values[0];
const building = values[1];
const uprns = values[2];
2019-05-27 13:26:29 -04:00
const buildingLike = values[3];
if (isBuilding && typeof (building) === 'undefined') {
2018-09-13 15:41:42 -04:00
context.status = 404
}
2018-09-11 18:30:17 -04:00
data.user = user;
data.building = building;
2019-05-27 13:26:29 -04:00
data.building_like = buildingLike;
if (data.building != null) {
data.building.uprns = uprns;
}
2018-09-13 15:41:42 -04:00
renderHTML(context, data, req, res)
}).catch(error => {
console.error(error);
data.user = undefined;
data.building = undefined;
2019-01-22 12:34:46 -05:00
data.building_like = undefined;
2018-10-04 17:44:04 -04:00
context.status = 500;
renderHTML(context, data, req, res);
});
2018-09-11 18:30:17 -04:00
}
2018-09-10 18:32:56 -04:00
2019-02-24 14:28:11 -05:00
function renderHTML(context, data, req, res) {
const markup = renderToString(
<StaticRouter context={context} location={req.url}>
2019-01-22 12:34:46 -05:00
<App user={data.user} building={data.building} building_like={data.building_like} />
</StaticRouter>
);
if (context.url) {
res.redirect(context.url);
} else {
res.status(context.status).send(
2019-02-24 14:28:11 -05:00
`<!doctype html>
<html lang="">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta charset="utf-8" />
<title>Colouring London</title>
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<style>
@font-face {
font-family: 'glacial_cl';
src: url('/fonts/glacialindifference-regular-webfont.woff2') format('woff2'),
url('/fonts/glacialindifference-regular-webfont.woff') format('woff');
font-weight: normal;
font-style: normal;
}
</style>
${
2019-05-27 11:39:16 -04:00
assets.client.css
? `<link rel="stylesheet" href="${assets.client.css}">`
: ''
}
${
2019-05-27 11:39:16 -04:00
process.env.NODE_ENV === 'production'
? `<script src="${assets.client.js}" defer></script>`
: `<script src="${assets.client.js}" defer crossorigin></script>`
}
</head>
<body>
<div id="root">${markup}</div>
<script>
window.__PRELOADED_STATE__ = ${serialize(data)}
</script>
</body>
</html>`
);
}
}
2018-09-10 05:44:32 -04:00
server.use('/tiles', tileserver);
2019-08-14 05:54:13 -04:00
server.use('/api', apiRouter);
2019-02-05 08:37:44 -05:00
export default server;