/**
* 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';
import bodyParser from 'body-parser';
import session from 'express-session';
import pgConnect from 'connect-pg-simple';
import App from './frontend/app';
import db from './db';
import { authUser, createUser, getUserById } from './user';
import { queryBuildingsAtPoint, queryBuildingsByReference, getBuildingById,
saveBuilding } from './building';
import tileserver from './tileserver';
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
const pgSession = pgConnect(session);
const sess = {
name: 'cl.session',
store: new pgSession({
pgPromise: db,
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 = {};
const data = {};
context.status = 200;
const building_id = parseBuildingURL(req.url);
if (isNaN(building_id)){
context.status = 404;
}
const is_building = (typeof(building_id) !== "undefined")
Promise.all([
req.session.user_id? getUserById(req.session.user_id) : undefined,
is_building? getBuildingById(building_id) : undefined
]).then(function(values){
const user = values[0];
const building = values[1];
if (is_building && typeof(building) === "undefined"){
context.status = 404
}
data.user = user;
data.building = building;
renderHTML(context, data, req, res)
}).catch(error => {
console.error(error);
data.user = undefined;
data.building = undefined;
contex.status = 500;
renderHTML(context, data, req, res);
});
}
function renderHTML(context, data, req, res){
const markup = renderToString(