Consider a NestJS controller method decorated with @UseInterceptors(CacheInterceptor). What is the behavior of this interceptor when the method is called multiple times with the same parameters?
import { Controller, Get, UseInterceptors } from '@nestjs/common'; import { CacheInterceptor } from '@nestjs/cache-manager'; @Controller('items') @UseInterceptors(CacheInterceptor) export class ItemsController { @Get() findAll() { console.log('Fetching items from DB'); return ['item1', 'item2']; } }
Think about how caching avoids repeated work and what the console output tells you.
The CacheInterceptor caches the response of the method after the first call. So the console log runs only once. Later calls return cached data without executing the method body again.
You want to enable caching for all controllers in your NestJS app using CacheInterceptor. Which code snippet correctly sets this up in main.ts?
Remember how to instantiate classes and pass them to global interceptors.
CacheInterceptor is a class and must be instantiated with new. Passing the class itself or calling it as a function causes errors.
Given this controller method:
@Post('create')
@UseInterceptors(CacheInterceptor)
createItem() {
return { success: true };
}Why does the CacheInterceptor not cache the response for this POST request?
Think about HTTP methods and typical caching rules.
CacheInterceptor caches only GET requests by default because POST requests usually change data and should not be cached.
You apply CacheInterceptor in a NestJS app but forget to import CacheModule. What will happen when a cached route is called?
Consider dependency injection and required modules in NestJS.
CacheInterceptor requires the cache manager provider from CacheModule. Without it, the app throws an error at runtime.
Given this controller method:
@Get('search')
@UseInterceptors(CacheInterceptor)
search(@Query('term') term: string) {
return { results: [term] };
}When a client calls /search?term=book, what cache key does CacheInterceptor use internally?
Think about how caching differentiates requests with different query parameters.
CacheInterceptor uses the full request URL including query parameters as the cache key to distinguish different queries.