convai / server /server.ts
Julien Chaumond
deploy script + change server port
c5ed897
raw
history blame
2.08 kB
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}`);
});