umijs / umi-request

A request tool based on fetch.
2.2k stars 336 forks source link

How to delete the cache for an endpoint and all the parameters? #220

Open javisperez opened 3 years ago

javisperez commented 3 years ago

Hi, is there a way to delete a specific key from the cache? I'm trying to make that once a NON-GET request is made, it clears out the cache for that endpoint (for all the params).

Example: GET /users?q=a would get cache, that's good. and I want that POST /users or PUT /users deletes the http://myapi/users key from the cache so on the next Fetch i get the updated data.

Is there a way to achieve this? using a middleware i have access to each method cache and if I pass the full key statically it works fine but I need a way to remove all the cache for that URL, for all the parameters.

This is what I'm currently doing and is working:

request.use(async (ctx, next) => {
  const { req, cache } = ctx
  if (req.options.method === 'POST') {
    const { url } = req
    for (const k of cache.cache.keys()) {
      const key = JSON.parse(k)
      if (key.url.includes(url) && key.method === 'GET') {
        cache.delete(key)
      }
    }
  }

  await next()
}, { core: true })

but that would interact with the whole cache on each request and that feels paintful, any better approach? Thanks.