File size: 2,084 Bytes
d0aa19c
 
 
 
 
 
 
c5ed897
d0aa19c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30358b4
d0aa19c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
const __ = require('./lib/Extensions');
import * as fs from 'fs';
import * as express from 'express';
import __rootDir from './lib/RootDirFinder';
import { c } from './lib/Log';
import * as Utils from './lib/Utils';
const app = express();
const PORT = 3200;
const __frontDir = __rootDir+`/front`;

// Express setup
app.set('trust proxy', 'loopback');
const staticHandler = express.static(__frontDir);
const staticHandlerNoHtml: express.RequestHandler = function(req, res, next) {
	if (req.path === '/' || req.path.endsWith('.html')) {
		return next();
	} else {
		return staticHandler(req, res, next);
	}
};
app.use(staticHandlerNoHtml);

const PERSONAS = {
	MAP: new Map<string, string>(), /// <- <slug, text>
	LST: [] as { slug: string, text: string }[],
};
(async () => {
	const o: Obj<string> = JSON.parse(await fs.promises.readFile(__rootDir+`/server/data/personas.json`, 'utf8'));
	for (const [k, v] of Object.entries(o)) {
		PERSONAS.MAP.set(k, v);
		PERSONAS.LST.push({ slug: k, text: v });
	}
	c.debug(`personas:loaded`);
})();


const templateHtml = async (slug: string, text: string): Promise<string> => {
	const jsStr = `window.PERSONA_ATLOAD = ${ JSON.stringify({ slug, text }) };`;
	/// Transform text. Should be the exact same function client-side.
	const persona = text.split('.').map(x => Utils.capitalize(x)).join(`.<br>`);
	let s = await fs.promises.readFile(__frontDir+`/index.html`, 'utf8');
	s = s.replace('/*  //u */', jsStr);
	s = s.replace('<!-- p -->', persona);
	return s;
}

// GET /

app.get('/', async function(req, res) {
	const p = PERSONAS.LST.randomItem();
	res.send(
		await templateHtml(p.slug, p.text)
	);
});

// GET persona/:slug

app.get('/persona/:slug', async function(req, res) {
	const slug: string = req.params.slug;
	const text = PERSONAS.MAP.get(slug);
	if (!text) {
		return res.redirect('/');
	}
	res.send(
		await templateHtml(slug, text)
	);
});

// GET /shuffle

app.get('/shuffle', function(req, res) {
	res.json(
		PERSONAS.LST.randomItem()
	);
});


// Start engine.

app.listen(PORT, () => {
	c.debug(`Running on ${PORT}`);
});