Skip to content

Conversation

@stemsmit
Copy link

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 added 2 commits July 16, 2018 21:02
This will allow setting res.express_redis_cache_expire to set the entry expiration
added the documentation for the new res.express_redis_cache_expire value
@stemsmit stemsmit changed the title Feature: Allow expiration to be set off of the Express Response object Feature: Allow expiration to be set off of the express response object Jul 18, 2018
@vksbansal
Copy link

please merge

@rawpixel-vincent
Copy link

rawpixel-vincent commented Jul 17, 2021

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants