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.
Cache decorators in NestJS
@Cacheable()
methodName() {
// method logic
}Use @Cacheable() above methods to cache their results.
You can customize cache time and keys with options.
getData with default settings.@Cacheable()
getData() {
return this.fetchFromDb();
}getUser results for 60 seconds.@Cacheable({ ttl: 60 })
getUser(id: string) {
return this.userService.findById(id);
}clearCache runs.@CacheEvict()
clearCache() {
// clears cache when called
}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.
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());
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.
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.
Practice
@Cacheable in a NestJS service method?Solution
Step 1: Understand cache decorator role
Cache decorators like@Cacheablesave the output of a method so it can be reused without recalculating.Step 2: Identify the benefit
This reuse speeds up responses by avoiding repeated work.Final Answer:
To store the method's result and reuse it for faster responses -> Option AQuick Check:
Cache decorators improve speed by storing results [OK]
- Thinking cache decorators log method calls
- Confusing cache with retry logic
- Assuming cache encrypts data
Solution
Step 1: Recall correct decorator syntax
The@Cacheabledecorator accepts an options object withttlas a key.Step 2: Identify correct object syntax
Correct syntax uses curly braces and colon:{ ttl: 10 }.Final Answer:
@Cacheable({ ttl: 10 }) -> Option AQuick Check:
Use object with ttl key inside @Cacheable [OK]
- Using parentheses with assignment inside decorator
- Using @CacheEvict to set TTL
- Using colon without braces
@Cacheable({ ttl: 5 })
async getData() {
console.log('Fetching data');
return 'data';
}What will be printed if
getData() is called three times within 5 seconds?Solution
Step 1: Understand caching effect on method calls
The first call runs the method and caches the result for 5 seconds.Step 2: Analyze subsequent calls within TTL
Calls within 5 seconds return cached result without running method, so no console log.Final Answer:
Fetching data (printed once) -> Option BQuick Check:
Cache prevents repeated method execution within TTL [OK]
- Assuming method runs every call ignoring cache
- Thinking cache disables method completely
- Confusing TTL with infinite caching
@Cacheable({ ttl: 10 })
async fetchData() {
return await this.httpService.get('url');
}
@CacheEvict()
clearCache() {
// clears cache
}What is the main issue with the
@CacheEvict usage here?Solution
Step 1: Understand
@CacheEvictpurpose@CacheEvictclears cached data, but needs to know which cache entry or key to clear.Step 2: Identify missing key or target
The code does not specify a key or target, so it cannot clear the intended cache.Final Answer:
It lacks a key or target to specify which cache to clear -> Option CQuick Check:
@CacheEvictneeds key/target to clear cache [OK]
- Using CacheEvict without specifying key
- Confusing CacheEvict with Cacheable
- Assuming async required for CacheEvict
Solution
Step 1: Understand caching and eviction roles
@Cacheablecaches method results;@CacheEvictclears cache entries.Step 2: Apply decorators to correct methods
Cache the fetch method result, and clear that cache when update method runs using@CacheEvictwith matching keys.Final Answer:
Use @Cacheable on the fetch method and @CacheEvict on the update method with matching cache keys -> Option DQuick Check:
Cache fetch, evict on update with matching keys [OK]
- Evicting cache on fetch method instead of update
- Caching update method results unnecessarily
- Not matching cache keys between decorators
Ready to prove it?
Pass the test and this pattern moves unknown
