From ea30e5dee5a50ff1a665b6933aaff7fe59814484 Mon Sep 17 00:00:00 2001 From: Bobby Wibowo Date: Fri, 19 Aug 2022 09:50:08 +0700 Subject: [PATCH] feat: enable persistent cache for nojs uploader also slight improvement to NunjucksRenderer class --- controllers/middlewares/NunjucksRenderer.js | 21 ++++++++++++++------- routes/nojs.js | 4 +--- 2 files changed, 15 insertions(+), 10 deletions(-) diff --git a/controllers/middlewares/NunjucksRenderer.js b/controllers/middlewares/NunjucksRenderer.js index a1f41c0..273692a 100644 --- a/controllers/middlewares/NunjucksRenderer.js +++ b/controllers/middlewares/NunjucksRenderer.js @@ -23,21 +23,28 @@ class NunjucksRenderer { #middleware (req, res, next) { // Inject render() method into Response on each requests - // If usePersistentCache, the rendered template will be cached forever (thus only use for absolutely static pages) - res.render = (path, params, usePersistentCache) => this.#render(res, path, params, usePersistentCache) + res.render = (...args) => this.#render(res, ...args) return next() } - #render (res, path, params, usePersistentCache) { + #render (res, path, context, usePersistentCache = false) { + // If usePersistentCache is true, the rendered templates will be cached forever, + // thus only use for absolutely static pages + if (!path) { + throw new Error('Missing Nunjucks template name.') + } + return new Promise((resolve, reject) => { const template = `${path}.njk` - const cached = this.#persistentCaches.get(template) - if (usePersistentCache && cached) { - return resolve(cached) + if (usePersistentCache) { + const cached = this.#persistentCaches.get(template) + if (cached) { + return resolve(cached) + } } - this.environment.render(template, params, (err, html) => { + this.environment.render(template, context, (err, html) => { if (err) { return reject(err) } diff --git a/routes/nojs.js b/routes/nojs.js index b4eafde..b74593c 100644 --- a/routes/nojs.js +++ b/routes/nojs.js @@ -5,11 +5,9 @@ const utils = require('./../controllers/utilsController') const config = require('./../config') routes.get('/nojs', async (req, res) => { - // TODO: Update res.render() to allow bypassing cache on demand, - // so that this GET route can instead re-use persistent cache return res.render('nojs', { config, utils, versions: utils.versionStrings - }) + }, !utils.devmode) }) // HyperExpress defaults to 250kb