feat: enable persistent cache for nojs uploader

also slight improvement to NunjucksRenderer class
This commit is contained in:
Bobby Wibowo 2022-08-19 09:50:08 +07:00
parent 19eac1d98a
commit ea30e5dee5
No known key found for this signature in database
GPG Key ID: 51C3A1E1E22D26CF
2 changed files with 15 additions and 10 deletions

View File

@ -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`
if (usePersistentCache) {
const cached = this.#persistentCaches.get(template)
if (usePersistentCache && cached) {
if (cached) {
return resolve(cached)
}
}
this.environment.render(template, params, (err, html) => {
this.environment.render(template, context, (err, html) => {
if (err) {
return reject(err)
}

View File

@ -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