express-redis-cache icon indicating copy to clipboard operation
express-redis-cache copied to clipboard

Feature: Allow expiration to be set off of the express response object

Open stemsmit opened this issue 6 years ago • 2 comments

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.

stemsmit avatar Jul 18 '18 05:07 stemsmit

please merge

vksbansal avatar Sep 19 '19 12:09 vksbansal

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
  );

rawpixel-vincent avatar Jul 17 '21 13:07 rawpixel-vincent