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 pathToRegexp from 'path-to-regexp';
const bodyParser = require('body-parser')
const session = require('express-session')
const pgSession = require('connect-pg-simple')(session);
import App from './frontend/app';
import { pool } from './db';
import { authUser, createUser, getUserById } from './user';
import { queryBuildingAtPoint } from './building';
import tileserver from './tileserver';
// 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 sess = {
name: 'cl.session',
store: new pgSession({
pool: pool,
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 data = {};
var re = pathToRegexp('/buildings/:building.html')
var matches = re.exec(req.url)
var building_id = undefined;
if (matches && matches.length === 2) {
building_id = matches[1]
}
console.log(`Building: ${building_id}`)
if (req.session.user_id) {
getUserById(req.session.user_id).then(function(user){
data.user = user;
renderHTML(data, req, res)
}).catch(function(){
renderHTML(data, req, res);
});
} else {
// getBuildingById() TODO load data server-side
renderHTML(data, req, res);
}
}
function renderHTML(data, req, res){
const context = {};
const markup = renderToString(