How to control cache in Nestjs?
Solution 1
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'));
}
Solution 2
You could also use another approach, you could use utils-decorators lib (npm install --save utils-decorators
) and take advantage of the AsyncMemoize decorator. Then you only need to add a decorator to you controller function:
import {memoizeAsync} from 'utils-decorators';
const cache = new Map();
class Controller {
@Get()
@memoizeAsync({cache: cache})
incrementCounter() {
this.counter++;
return this.counter;
}
@Get('reset')
resetCache() {
// do whatever you want with the cache map.
}
}
pingze
Updated on June 14, 2022Comments
-
pingze almost 2 years
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?
-
Sohel Ahmed Mesaniya almost 4 yearsHi @kim-kern . Thanks for the answer. I would like to know what is the data type of
cacheManager
variable (@Inject(CACHE_MANAGER) private cacheManager
) -
Kim Kern almost 4 years@SohelAhmedM Try
npm install --save-dev @types/cache-manager
-
Sohel Ahmed Mesaniya almost 4 yearsI have added a simple minimal nestjs-redis-cache example - gist.github.com/SOHELAHMED7/f7396fb7711aad9538e149e1b811b53c
-
Vallie over 3 yearsIs there a way we can enable and disable entire caching feature via a flag(true/false) in config
-
Kim Kern over 3 years@Vallie It's hard to answer your question without seeing more details. When is the flag set? Statically on server start or dynamically? How is it set? ... Please open a new question and include a code example that describes your use case. :-)
-
Vallie over 3 yearsPosted here stackoverflow.com/questions/63942382/…