Nestjs how to clear ( reset ) all cache

Viewed 6054

I'm building an API and the data get updated every day at 3 am and need to clear all cached endpoints whatever is!

I'm using the CacheModule and the decorator @UserInterceptor(CacheInterceptor) to cache whatever I need in the controller.

there a Cron function that runs every day at 3 am to update the content, I need to know what the code should put in that method to clear all cache.

2 Answers

You can inject the underlying cache manager instance:

constructor(@Inject(CACHE_MANAGER) protected readonly cacheManager) {} 

And then use it to delete the caches for all keys:

const keys = await this.cacheManager.keys()
await this.cacheManager.del(keys)

According to the official NestJs docs (July 2022), they offer a .reset() method to "clear the entire cache". This examples assumes you're using the naming convention in their docs, where cacheManager is the locally scoped & injected CACHE_MANAGER from @nestjs/common and "Cache" from cache-manager package.

// inside the class constructor
constructor(@Inject(CACHE_MANAGER) private cacheManager: Cache) {}
// and then inside a class method
await this.cacheManager.reset();

Reference: https://docs.nestjs.com/techniques/caching

Related