问题
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?
回答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'));
}
回答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.
}
}
来源:https://stackoverflow.com/questions/55156379/how-to-control-cache-in-nestjs