Clear template cache on /reload (#734)

This commit is contained in:
Calvin Montgomery 2018-03-05 21:46:58 -08:00
parent 247cf770d0
commit 81e1947656
3 changed files with 46 additions and 10 deletions

View file

@ -2,7 +2,7 @@
"author": "Calvin Montgomery",
"name": "CyTube",
"description": "Online media synchronizer and chat",
"version": "3.55.1",
"version": "3.55.2",
"repository": {
"url": "http://github.com/calzoneman/sync"
},

View file

@ -30,6 +30,7 @@ function handleLine(line) {
if (line === '/reload') {
LOGGER.info('Reloading config');
Config.load('config.yaml');
require('./web/pug').clearCache();
} else if (line.indexOf('/switch') === 0) {
const args = line.split(' ');
args.shift();
@ -124,7 +125,19 @@ if (Config.get('service-socket.enabled')) {
LOGGER.info('Opening service socket');
const ServiceSocket = require('./servsock');
const sock = new ServiceSocket();
sock.init(handleLine, Config.get('service-socket.socket'));
sock.init(
line => {
try {
handleLine(line);
} catch (error) {
LOGGER.error(
'Error in UNIX socket command handler: %s',
error.stack
);
}
},
Config.get('service-socket.socket')
);
}
let stdinbuf = '';
@ -133,7 +146,11 @@ process.stdin.on('data', function (data) {
if (stdinbuf.indexOf('\n') !== -1) {
let line = stdinbuf.substring(0, stdinbuf.indexOf('\n'));
stdinbuf = stdinbuf.substring(stdinbuf.indexOf('\n') + 1);
handleLine(line);
try {
handleLine(line);
} catch (error) {
LOGGER.error('Command line input handler failed: %s', error.stack);
}
}
});

View file

@ -3,7 +3,9 @@ var fs = require("fs");
var path = require("path");
var Config = require("../config");
var templates = path.join(__dirname, "..", "..", "templates");
var cache = {};
const cache = new Map();
const LOGGER = require('@calzoneman/jsli')('web/pug');
/**
* Merges locals with globals for pug rendering
@ -42,16 +44,21 @@ function sendPug(res, view, locals) {
locals.loginName = nvl(locals.loginName, res.locals.loginName);
locals.superadmin = nvl(locals.superadmin, res.locals.superadmin);
if (!(view in cache) || Config.get("debug")) {
let renderFn = cache.get(view);
if (!renderFn || Config.get("debug")) {
LOGGER.debug("Loading template %s", view);
var file = path.join(templates, view + ".pug");
var fn = pug.compile(fs.readFileSync(file), {
renderFn = pug.compile(fs.readFileSync(file), {
filename: file,
pretty: !Config.get("http.minify")
});
cache[view] = fn;
cache.set(view, renderFn);
}
var html = cache[view](merge(locals, res));
res.send(html);
res.send(renderFn(merge(locals, res)));
}
function nvl(a, b) {
@ -59,6 +66,18 @@ function nvl(a, b) {
return a;
}
function clearCache() {
let removed = 0;
for (const key of cache.keys()) {
cache.delete(key);
removed++;
}
LOGGER.info('Removed %d compiled templates from the cache', removed);
}
module.exports = {
sendPug: sendPug
sendPug: sendPug,
clearCache: clearCache
};