NestJS
Cache
Caching responses and data in NestJS using Cache Manager.
App Module: Importing and configuring the CacheModule.
app.module.ts
typescript
import { Module } from '@nestjs/common';
import { CacheModule } from '@nestjs/cache-manager';
import { AppController } from './app.controller';
import { AppService } from './app.service';
@Module({
imports: [
CacheModule.register({
ttl: 5000, // milliseconds
max: 100, // maximum number of items in cache
isGlobal: true,
}),
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
Auto-Caching: Using CacheInterceptor to automatically cache route responses.
app.controller.ts
typescript
import { Controller, Get, UseInterceptors } from '@nestjs/common';
import { CacheInterceptor, CacheKey, CacheTTL } from '@nestjs/cache-manager';
@Controller('users')
@UseInterceptors(CacheInterceptor)
export class UsersController {
@Get()
findAll() {
// This response will be cached automatically
return [{ id: 1, name: 'John Doe' }];
}
@Get('custom')
@CacheKey('custom_key')
@CacheTTL(10000) // override default TTL
findCustom() {
return 'This response is cached for 10 seconds under "custom_key"';
}
}
Manual Caching: Injecting CacheManager to manually get, set, and delete cache keys.
app.service.ts
typescript
import { Injectable, Inject } from '@nestjs/common';
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { Cache } from 'cache-manager';
@Injectable()
export class AppService {
constructor(@Inject(CACHE_MANAGER) private cacheManager: Cache) {}
async processData() {
// Check if value exists in cache
const cachedData = await this.cacheManager.get('my-data');
if (cachedData) {
return cachedData;
}
// Process data...
const newData = { status: 'processed', timestamp: Date.now() };
// Set value in cache
await this.cacheManager.set('my-data', newData, 30000); // 30 seconds TTL
return newData;
}
async clearCache() {
await this.cacheManager.del('my-data');
// or await this.cacheManager.reset(); to clear everything
}
}