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?
A CacheManager is the primary mechanism for retrieving a Cache instance, and is often used as a starting point to using the Cache .
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.
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'));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With