From e13dbd04f499623b0f48415bb43459ee9cd0d040 Mon Sep 17 00:00:00 2001 From: Matt Weber <1062734+mweberxyz@users.noreply.github.com> Date: Mon, 26 Feb 2024 19:35:46 -0500 Subject: [PATCH] perf: cache layout access check --- index.js | 16 +++++++++++++--- test/test-handlebars.js | 7 ++++++- 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/index.js b/index.js index 8b2b67e..ad01505 100644 --- a/index.js +++ b/index.js @@ -645,13 +645,23 @@ async function fastifyView (fastify, opts) { } function hasAccessToLayoutFile (fileName, ext) { + const layoutKey = `layout-${fileName}-${ext}` + let result = fastify[viewCache].get(layoutKey) + + if (typeof result === 'boolean') { + return result + } + try { accessSync(join(templatesDir, getPage(fileName, ext))) - - return true + result = true } catch (e) { - return false + result = false } + + fastify[viewCache].set(layoutKey, result) + + return result } } diff --git a/test/test-handlebars.js b/test/test-handlebars.js index c49374f..d4e5999 100644 --- a/test/test-handlebars.js +++ b/test/test-handlebars.js @@ -331,7 +331,7 @@ test('fastify.view with handlebars engine with layout option on render', t => { }) test('fastify.view with handlebars engine with invalid layout option on render should throw', t => { - t.plan(3) + t.plan(5) const fastify = Fastify() const handlebars = require('handlebars') @@ -349,6 +349,11 @@ test('fastify.view with handlebars engine with invalid layout option on render s t.ok(err instanceof Error) t.equal(err.message, 'unable to access template "./templates/invalid-layout.hbs"') }) + // repeated for test coverage of layout access check lru + fastify.view('./templates/index-for-layout.hbs', data, { layout: './templates/invalid-layout.hbs' }, (err, compiled) => { + t.ok(err instanceof Error) + t.equal(err.message, 'unable to access template "./templates/invalid-layout.hbs"') + }) }) })