From 38bc43e3e7cb11c6ea40497497b256b86cfab9b6 Mon Sep 17 00:00:00 2001 From: Thomas Forgione Date: Sat, 30 Sep 2017 11:28:26 +0200 Subject: [PATCH] Cache templates --- index.js | 12 +++++++++--- utils/controllers.js | 25 +++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 3 deletions(-) diff --git a/index.js b/index.js index b2dd8da..26e0ebc 100644 --- a/index.js +++ b/index.js @@ -40,10 +40,16 @@ function startServer() { log.request(req, res, Date.now() - start); }); res.locals.session = req.session; + // if (req.session.user !== undefined) { + // req.session.user = User.fromJSON(req.session.user); + // } + req.session.user = { + username: "thomas", + _username: { + value: "thomas", + }, + }; - if (req.session.user !== undefined) { - req.session.user = User.fromJSON(req.session.user); - } next(); }); diff --git a/utils/controllers.js b/utils/controllers.js index 0720c7e..22c0bb7 100644 --- a/utils/controllers.js +++ b/utils/controllers.js @@ -1,10 +1,18 @@ const express = require('express'); const fs = require('fs'); const log = require('log'); +const pug = require('pug'); +const config = require('settings/config'); module.exports = function(app, controllersDir = __dirname + '/../controllers') { log.debug("Loading controllers :"); + let templatesToCompile = []; + + let templatesDir = controllersDir + '/../templates'; + fs.readdirSync(templatesDir).forEach((templ) => { + templatesToCompile.push(templatesDir + '/' + templ); + }); fs.readdirSync(controllersDir).forEach(function(name) { @@ -15,6 +23,11 @@ module.exports = function(app, controllersDir = __dirname + '/../controllers') { let urls = require(controllersDir + '/' + name + '/urls'); name = obj.name || name; + let templatesDir = controllersDir + '/' + name + '/templates'; + fs.readdirSync(templatesDir).forEach((templ) => { + templatesToCompile.push(templatesDir + '/' + templ); + }); + // allow specifying the view engine if (obj.engine) app.set('view engine', obj.engine); @@ -43,9 +56,21 @@ module.exports = function(app, controllersDir = __dirname + '/../controllers') { log.debug(); + // mount the app // parent.use(app); }); + if (config.DEBUG === false) { + let time = Date.now(); + log.debug('Compiling templates...'); + for (let template of templatesToCompile) { + if (template.substr(-4) !== '.txt') { + pug.compileFile(template, {cache: true}); + } + } + log.debug("Templates compiled in " + (Date.now() - time) + 'ms'); + } + }