Consider a NestJS service method decorated with @Cacheable() that returns a random number. What will happen when you call this method twice in a row?
import { Cacheable } from '@nestjs/cache-manager'; class RandomService { @Cacheable() getRandom() { return Math.random(); } } const service = new RandomService(); const first = service.getRandom(); const second = service.getRandom(); console.log(first === second);
Think about what caching does to method results.
The @Cacheable() decorator caches the result of the method. So the first call stores the random number, and the second call returns the cached value, making both equal.
In NestJS, if a method is decorated with @CacheEvict(), when does the cache get cleared?
import { CacheEvict } from '@nestjs/cache-manager'; class UserService { @CacheEvict() updateUser(id: string, data: any) { // update user logic return true; } }
Think about when you want to remove stale data after an update.
The @CacheEvict() decorator clears the cache after the method finishes successfully to ensure stale data is removed.
Choose the correct way to set a custom cache key and TTL (time to live) for a method in NestJS.
import { CacheKey, CacheTTL, Cacheable } from '@nestjs/cache-manager'; class ProductService { @Cacheable() @CacheKey('custom_key') @CacheTTL(120) getProduct(id: string) { return { id, name: 'Product' }; } }
Remember the order decorators are applied matters in NestJS.
Decorators are applied bottom-up. @Cacheable() must be the last decorator so it wraps the others properly.
Given a method decorated with @Cacheable() that returns a Promise, what happens if you call it without await and try to cache the result?
import { Cacheable } from '@nestjs/cache-manager'; class AsyncService { @Cacheable() async fetchData() { return 'data'; } } const service = new AsyncService(); const result = service.fetchData(); console.log(typeof result);
Think about what happens when you don't await an async function.
Without await, the method returns a Promise object. The cache stores this Promise, not the resolved value, so the type is 'object'.
Choose the true statement about how NestJS cache decorators work.
Recall the purpose of each decorator.
@CacheEvict is used to clear cache entries manually. @CacheKey sets the cache key, and @CacheTTL sets the expiration time. @Cacheable caches results but does not auto-invalidate on data changes.