Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to control cache in Nestjs?

I read the doc of nestjs recently, and learned something from it.

But I found something that puzzled me.

In Techniques/Caching, the doc shows me to use a decorator like @UseInterceptors(CacheInterceptor) on a controller to cache its response (default track by route).

I wrote a testcase and found it's useful. But I didn't find any explanation to show how to clean the cache. That means I have to wait for the cache to expire.

In my opinion, a cache store must provide an API to clear the cache by key, so that it can update the cache when data changes (by explicitly calling a clear API).

Is there any way to do that?

like image 393
pingze Avatar asked Mar 14 '19 06:03

pingze


People also ask

What is Cache Manager?

A CacheManager is the primary mechanism for retrieving a Cache instance, and is often used as a starting point to using the Cache .


1 Answers

You can inject the underlying cache-manager instance with @Inject(CACHE_MANAGER). On the cache-manager instance you can then call the method del(key, cb) to clear the cache for a specified key, see the docs.

Example

counter = 0;
constructor(@Inject(CACHE_MANAGER) private cacheManager) {}

// The first call increments to one, the preceding calls will be answered by the cache
// without incrementing the counter. Only after you clear the cache by calling /reset
// the counter will be incremented once again.
@Get()
@UseInterceptors(CacheInterceptor)
incrementCounter() {
  this.counter++;
  return this.counter;
}

// Call this endpoint to reset the cache for the route '/'
@Get('reset')
resetCache() {
  const routeToClear = '/';
  this.cacheManager.del(routeToClear, () => console.log('clear done'));
}

Edit nest-clear-cache

like image 52
Kim Kern Avatar answered Nov 01 '22 20:11

Kim Kern