How to cache views so files don't need to be re-read and re-rendered

221 views Asked by At

I have these view render calls:

router.get('/mcn', (req, res) => {
  res.render('product/mcn', { layout: 'product/layout', contactKey: 'mcn' });
});

router.get('/agency', (req, res) => {
  res.render('product/agency', { layout: 'product/layout', contactKey: 'agency' });
});

router.get('/esports', (req, res) => {
  res.render('product/esports', { layout: 'product/layout', contactKey: 'esports' });
});

router.get('/brand', (req, res) => {
  res.render('product/brand', { layout: 'product/layout', contactKey: 'brand' });
});

router.get('/analytics', (req, res) => {
  res.render('product/analytics', { layout: 'product/layout', contactKey: 'analytics' });
});

router.get('/rightsmanagement', (req, res) => {
  res.render('product/content-id', { layout: 'product/layout', contactKey: 'content-id' });
});

as you may notice - there is no dynamic data being passed. So I am wondering how I can cache these views? Something like this:

const pug = require('pug');

 {
    const templateStr = fs.readFileSync(path.resolve(__dirname +'/../views/product/content-id'));

    const fn = pug.compile(templateStr, {});

    const html = fn({ layout: 'product/layout', contactKey: 'content-id' });

    router.get('/rightsmanagement', (req, res) => {
      res.send(html);
    });

  }

is that about right? I think I am missing some headers? doesn't anyone know what the right headers are?

1

There are 1 answers

0
djs On BEST ANSWER

I'm not sure what your doing with the pug.compile() and all, but you could use the Cache-Control header with the max-age value to tell the browser to cache whatever you send along:

router.get('/rightsmanagement', (req, res) => {
  // set max-age to whatever you think is best
  res.set('Cache-Control', 'max-age=31536000');
  res.send(html);
});

You could possibly use this as middleware to setup the renders, as req.path includes the only dynamic content in your handlers, except for the special case of the rightsmanagment route:

const renderCacheView = (req, res, next) => {
  let path = req.path;
  if (path === 'rightsmanagement') path = 'content-id';
  // set max-age to whatever you think is best
  res.set('Cache-Control', 'max-age=31536000');
  res.render(`product/${path}`, { layout: 'product/layout', contactKey: path});
};

I think you could even get away with this instead of writing so many routes, by utilizing the fact that you can pass a regular expression as the path:

router.get(/mcn|agency|esports|brand|analytics|rightsmanagement/, renderCacheView);