Kikobeats/cacheable-response

Possible to flush cache on running instance without having to restart?

genox opened this issue · 2 comments

genox commented

Hi there,

Is there an option (didn't find any in the documentation, so I guess this is a feature request disguised as a question :-) ) to forcefully flush the cache of a running express instance which uses this library to cache requests?

Use case: I use a headless CMS to hydrate a SSR react app. The headless CMS is able to call web hooks on create/update/delete actions. My plan would be to implement a route in express (web hook endpoint) to allow cache being flushed whenever a CMS user changes content, as this can cause the entire page to be stale (e.g. changing menu items).

Maybe there's already a hidden query parameter for that, like force?

Did you note you can refresh a single URL using force query parameter?

curl https://myserver.dev/user # MISS (first access)
curl https://myserver.dev/user # HIT (served from cache)
curl https://myserver.dev/user # HIT (served from cache)
curl https://myserver.dev/user?force=true # MISS (forcing invalidation)

If you want to flush completely the cache:

  1. Pass an instance of Keyv here.
  2. Use .clear method for doing that when you want!

For example:

const cacheableResponse = require('cacheable-response')
const Keyv = require('keyv')

const cache = new Keyv()

const ssrCache = cacheableResponse({
  cache, // setup your cache here
  get: ({ req, res }) => ({
    data: doSomething(req),
    ttl: 7200000 // 2 hours
  }),
  send: ({ data, res, req }) => res.send(data)
})


// connect cacheable-response with express
app.use((req, res) => ssrCache({ req, res }))

// be possible flush on demand 
app.get('/flush', function (req, res) {
  await cache.clear()
  // I send 205 code to say "hey, cache is flushed"
  // https://httpstatuses.com/205
  res.status(205).send())
})
genox commented

Yes, this should do the trick. Thanks a lot!