Performance: Cache interceptor
This affects server response time and client perceived load speed by reducing repeated processing and data fetching.
import { CacheInterceptor, ExecutionContext, Injectable } from '@nestjs/common'; @Injectable() export class CustomCacheInterceptor extends CacheInterceptor { trackBy(context: ExecutionContext): string | undefined { const request = context.switchToHttp().getRequest(); return request.url; // Cache key based on URL } }
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common'; import { Observable } from 'rxjs'; @Injectable() export class NoCacheInterceptor implements NestInterceptor { intercept(context: ExecutionContext, next: CallHandler): Observable<any> { // Always process request without caching return next.handle(); } }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| No cache interceptor | N/A (server-side) | N/A | N/A | [X] Bad |
| Cache interceptor with URL key | N/A (server-side) | N/A | N/A | [OK] Good |
CacheInterceptor in NestJS?@UseInterceptors() decorator above methods or controllers./hello?
import { Controller, Get, UseInterceptors } from '@nestjs/common';
import { CacheInterceptor } from '@nestjs/cache-manager';
@Controller()
export class HelloController {
private count = 0;
@UseInterceptors(CacheInterceptor)
@Get('hello')
getHello() {
this.count++;
return `Hello count: ${this.count}`;
}
}import { Controller, Get, UseInterceptors } from '@nestjs/common';
import { CacheInterceptor } from '@nestjs/cache-manager';
@Controller()
export class TestController {
@UseInterceptors(CacheInterceptor())
@Get('test')
test() {
return 'Test response';
}
}@UseInterceptors().trackBy method to define how keys are generated.@UseInterceptors() is invalid. Setting keys in constructor or using @CacheKey decorator does not exist in NestJS.trackBy method to return a custom key -> Option APass the test and this pattern moves unknown