Skip to content

Instantly share code, notes, and snippets.

@IvanAdmaers
Last active January 22, 2022 12:57
Show Gist options
  • Save IvanAdmaers/4dd840c0972ae8eec6d5acb7f7f60cdf to your computer and use it in GitHub Desktop.
Save IvanAdmaers/4dd840c0972ae8eec6d5acb7f7f60cdf to your computer and use it in GitHub Desktop.
Express Caching Middleware

Usage

router.get('/', cacheMiddleware(60 * 60), mainController);
const cache = require('memory-cache-pro');
const isProduction = process.env.NODE_ENV === 'production';
/**
* This middleware makes caching
*
* @param {number} duration - Cache duration in seconds
* @param {boolean=} cacheInDevelopment - Should it cache in development mode
*/
const cacheMiddleware = (duration, cacheInDevelopment = false) => {
return (req, res, next) => {
if (!isProduction && !cacheInDevelopment) {
return next();
}
const url = req.originalUrl ?? req.url;
const key = `__express__cache__url__${url}`;
const cacheContent = cache.get(key);
if (cacheContent) {
return res.send(cacheContent);
}
res.sendResponse = res.send;
res.send = (body) => {
cache.put(key, body, duration * 1000);
res.sendResponse(body);
};
next();
};
};
module.exports = cacheMiddleware;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment