router.get('/', cacheMiddleware(60 * 60), mainController);
Last active
January 22, 2022 12:57
-
-
Save IvanAdmaers/4dd840c0972ae8eec6d5acb7f7f60cdf to your computer and use it in GitHub Desktop.
Express Caching Middleware
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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