Consider a NestJS controller method using a custom cache key function. What will be the effect on caching behavior?
import { Controller, Get } from '@nestjs/common'; import { CacheKey, CacheTTL } from '@nestjs/cache-manager'; @Controller('items') export class ItemsController { @Get() @CacheKey('custom_key') @CacheTTL(30) findAll() { return ['item1', 'item2']; } }
Think about what the @CacheKey decorator does in NestJS.
The @CacheKey decorator sets a fixed key for caching the method's response. This means the cache always uses the given string as the key, ignoring any request parameters.
Which of the following code snippets correctly sets a custom cache key for a controller method in NestJS?
Remember how decorators accept string literals for keys.
The @CacheKey decorator requires a string argument to specify the cache key. Option A correctly passes a string literal.
Given this code, why does the cache not store separate responses for different user IDs?
import { Controller, Get, Param } from '@nestjs/common'; import { CacheKey } from '@nestjs/cache-manager'; @Controller('users') export class UsersController { @Get(':id') @CacheKey('user_data') getUser(@Param('id') id: string) { return { id, name: 'User ' + id }; } }
Think about how cache keys identify cached data.
The fixed cache key 'user_data' causes all responses to be stored under the same key, so different user IDs overwrite each other in the cache.
Which approach correctly creates dynamic cache keys based on method parameters in NestJS?
Think about how to customize cache keys beyond static strings.
The @CacheKey decorator only accepts static strings. To create dynamic keys based on parameters, you need a custom interceptor that builds keys at runtime.
Given the following NestJS controller and custom interceptor, what cache keys are used and what is the output after two calls with different parameters?
import { CacheInterceptor, ExecutionContext, Injectable, Controller, Get, Param, UseInterceptors } from '@nestjs/common'; @Injectable() class CustomCacheInterceptor extends CacheInterceptor { trackBy(context: ExecutionContext): string | undefined { const request = context.switchToHttp().getRequest(); const id = request.params.id; return `user_${id}`; } } @Controller('users') @UseInterceptors(CustomCacheInterceptor) export class UsersController { @Get(':id') getUser(@Param('id') id: string) { return { id, name: 'User ' + id }; } } // Calls: // 1) GET /users/1 // 2) GET /users/2
Look at how the custom interceptor builds the cache key.
The custom interceptor uses the route parameter 'id' to build unique cache keys 'user_1' and 'user_2'. Each call caches and returns the correct user data separately.