0
0
NestJSframework~5 mins

Cache decorators in NestJS

Choose your learning style9 modes available
Introduction

Cache decorators help store and reuse data to make your app faster. They save results so you don't have to do the same work again.

When you want to speed up responses for repeated requests.
When fetching data from slow sources like databases or APIs.
When you want to reduce server load by avoiding repeated calculations.
When you want to improve user experience by delivering data faster.
Syntax
NestJS
@Cacheable()
methodName() {
  // method logic
}

Use @Cacheable() above methods to cache their results.

You can customize cache time and keys with options.

Examples
This caches the result of getData with default settings.
NestJS
@Cacheable()
getData() {
  return this.fetchFromDb();
}
This caches getUser results for 60 seconds.
NestJS
@Cacheable({ ttl: 60 })
getUser(id: string) {
  return this.userService.findById(id);
}
This decorator clears cache when clearCache runs.
NestJS
@CacheEvict()
clearCache() {
  // clears cache when called
}
Sample Program

This example shows a method getNumber that increases a counter. Using @Cacheable, the first call caches the result. The second call returns the cached value, so the counter does not increase again within 10 seconds.

NestJS
import { Injectable, Cacheable } from '@nestjs/common';

@Injectable()
export class DataService {
  private counter = 0;

  @Cacheable({ ttl: 10 })
  getNumber() {
    this.counter++;
    return this.counter;
  }
}

// Simulated calls
const service = new DataService();
console.log(service.getNumber());
console.log(service.getNumber());
OutputSuccess
Important Notes

Cache decorators work best for methods with stable results.

Remember to set a proper ttl (time to live) to avoid stale data.

Use @CacheEvict to clear cache when data changes.

Summary

Cache decorators store method results to speed up repeated calls.

Use @Cacheable to cache and @CacheEvict to clear cache.

Set cache duration with ttl to keep data fresh.