Complete the code to import the CacheInterceptor from NestJS.
import { [1] } from '@nestjs/common';
The CacheInterceptor is imported from @nestjs/common to enable caching features.
Complete the code to create a custom cache key by overriding the trackBy method.
export class CustomCacheInterceptor extends CacheInterceptor { protected trackBy(context: ExecutionContext): string | undefined { const request = context.switchToHttp().getRequest(); return request.method + ':' + [1]; } }
The cache key is often based on the HTTP method and the request URL to uniquely identify requests.
Fix the error in the custom cache key function to correctly handle query parameters.
protected trackBy(context: ExecutionContext): string | undefined {
const request = context.switchToHttp().getRequest();
const key = request.method + ':' + request.url + '?' + [1];
return key;
}Query parameters are accessed via request.query to include them in the cache key.
Fill both blanks to create a cache key that includes method, URL, and a user ID from headers.
protected trackBy(context: ExecutionContext): string | undefined {
const request = context.switchToHttp().getRequest();
const userId = request.headers['[1]'];
return request.method + ':' + request.url + ':' + [2];
}The user ID is often sent in a custom header like x-user-id. We retrieve it and include it in the cache key.
Fill all three blanks to define a custom cache interceptor class with a trackBy method that uses method, URL, and a query param 'lang'.
import { CacheInterceptor, ExecutionContext } from '@nestjs/common'; export class CustomCacheInterceptor extends [1] { protected trackBy(context: [2]): string | undefined { const request = context.switchToHttp().getRequest(); const lang = request.query['[3]']; return request.method + ':' + request.url + ':' + lang; } }
The class extends CacheInterceptor, the method argument is of type ExecutionContext, and the query parameter key is 'lang'.