From 032ec9aa90649c92a4d603cc436264467f5588d7 Mon Sep 17 00:00:00 2001 From: Stephen Smith Date: Mon, 16 Jul 2018 21:02:04 -0500 Subject: [PATCH 1/2] add expiration setter on express response This will allow setting res.express_redis_cache_expire to set the entry expiration --- lib/ExpressRedisCache/route.js | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/lib/ExpressRedisCache/route.js b/lib/ExpressRedisCache/route.js index 6b46ea4..38124fa 100644 --- a/lib/ExpressRedisCache/route.js +++ b/lib/ExpressRedisCache/route.js @@ -146,7 +146,14 @@ module.exports = (function () { else if ( typeof options[1] === 'number' || typeof options[1] === 'object') { expire = options[1]; } - + + + // If a cache expiration has been explicitly attached to `res` then use it as expiration + + if ( res.express_redis_cache_expire ) { + expire = res.express_redis_cache_expire; + } + var binary = false; if ( typeof options[0] === 'object' && typeof options[0].binary === 'boolean' ) { binary = options[0].binary; From 59db84b1ba7248c26676b097db3088c190782041 Mon Sep 17 00:00:00 2001 From: Stephen Smith Date: Mon, 16 Jul 2018 23:25:19 -0500 Subject: [PATCH 2/2] update readme to reflect new option added the documentation for the new res.express_redis_cache_expire value --- README.md | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/README.md b/README.md index 53512c6..4e6d0e8 100644 --- a/README.md +++ b/README.md @@ -199,6 +199,39 @@ cache.route('index', 5000); cache.route({ prefix: 'test' }, 5000); ``` +Also, you can use `res.express_redis_cache_expire` to specify the expiration of the entry such as: + +```js +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'); + } + + ); +``` You can also provide a hash of status code / expiration values if you for example want to retry much sooner in failure cases (403/404/500/etc). Status ranges can be specified via `4xx`/`5xx`. You must provide a default value (`xxx`). The most specific rule will be used. For example, if the status code is 200, and there are expirations set for 200, 2xx, and xxx, the expiration for 200 will be used. ```js