express-redis-cache
express-redis-cache copied to clipboard
Feature: Allow expiration to be set off of the express response object
I noticed this PR has been submitted before but no explanation as to why fandaa closed it. I believe this feature would be useful. The code snippet below(which has been added to the README.md in this PR) is an example of the added feature.
app.get('/statistic/:range',
// middleware to define cache expiration
function (req, res, next) {
const dayInSeconds = 86400;
const rangeExpirationMappings = {
"past-year": dayInSeconds * 30, // Expires in 1 month
"past-month": dayInSeconds * 7, // Expires in 7 days
"past-week": dayInSeconds // Expires in 1 day
}
// set cache expiration
if ( rangeExpirationMappings[req.params.range] ) {
res.express_redis_cache_expire = rangeExpirationMappings[req.params.range];
}
next();
},
// cache middleware
cache.route(),
// content middleware
function (req, res) {
res.render('stats');
}
);
If any other information is needed please let me know.
please merge
came here for something else but if someone interested you could achieve this by wrapping the redis cache middleware:
api.get(
'/endpoint',
/**
* Conditions to bypass the cache.
* @param {import('express').Request} req
* @param {import('express').Response} res
* @param {import('express').NextFunction} next
*/
async (req, res, next) => {
req.redisCacheTime = 3600; // 1 hour.
if (condition) {
req.redisCacheTime = 900; // 15 minutes.
}
if (anotherCondition) {
res.use_express_redis_cache = false; // disable redis cache completely
}
// note that those condition must be based on url parameters (query or params),
// otherwise (even if I personally won't recommend that, there is valid use case) you want to mutate the res.express_redis_cache_name options
next();
},
(req, res, next) =>
redisCache.route({
expire: {
'2xx': req.redisCacheTime,
'3xx': req.redisCacheTime,
'4xx': 10,
'5xx': 10,
xxx: 1,
},
})(req, res, next),
yourResponseCallback
);