Performance: Cache decorators
Cache decorators improve response time by storing results and reducing repeated processing, impacting page load speed and interaction responsiveness.
@UseInterceptors(CacheInterceptor) async getData() { return await this.service.fetchData(); }
async getData() { // heavy computation or DB call return await this.service.fetchData(); }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| No caching | N/A | N/A | N/A | [X] Bad |
| With cache decorators | N/A | N/A | N/A | [OK] Good |
@Cacheable in a NestJS service method?@Cacheable save the output of a method so it can be reused without recalculating.@Cacheable decorator accepts an options object with ttl as a key.{ ttl: 10 }.@Cacheable({ ttl: 5 })
async getData() {
console.log('Fetching data');
return 'data';
}getData() is called three times within 5 seconds?@Cacheable({ ttl: 10 })
async fetchData() {
return await this.httpService.get('url');
}
@CacheEvict()
clearCache() {
// clears cache
}@CacheEvict usage here?@CacheEvict purpose@CacheEvict clears cached data, but needs to know which cache entry or key to clear.@CacheEvict needs key/target to clear cache [OK]@Cacheable caches method results; @CacheEvict clears cache entries.@CacheEvict with matching keys.Pass the test and this pattern moves unknown